DEV Community

miraj  patel
miraj patel

Posted on

React.js/Redux + Drag&Drop

In my most recent project, 'GreenHouse', users manage spaces that may contain any number of house plants. One of my goals with this project was to incorporate as much interactive functionality as I could to provide a fluid user experience. Drag-and-drop was a big step towards this objective. I wanted to be able to drag plants between spaces and update the containing room components appropriately, and accomplishing this was relatively straight-forward to incorporate with my Redux build.

We start off with two basic components: a PlantCard and a SpaceCard. I'm more familiar with class components, but this functionality might also be achievable using functional components.

First, our PlantCard

`## PlantCard.js

import React, { Component } from 'react';

class PlantCard extends Component {

# unrelated PlantCard functionality goes up here

render() {
return(

    # plant information goes here

);
}
}

export default PlantCard`

`## SpaceCard.js

import React, { Component } from 'react';

class SpaceCard extends Component {

# unrelated SpaceCard functionality goes up here

render() {
return(



# space info goes here


{this.props.plants.map(plant => )}


);
}
}

export default SpaceCard`

With our basic components set up, we can build in our drag & drop functionality. First, we'll tell our PlantCard about being dragged around.

`


dragStart = event = {
const plant = JSON.stringify(this.props.plant);
event.dataTransfer.setData('plant', plant);
}

`
When the mouse button is held and dragged away from a Plant component, the component's plant prop is stored in the DataTransfer object under the keyword plant.

As a safeguard to prevent strange graphical issues, we can also add this function to our PlantCard class component:

Top comments (0)