Build Drag and Drop Component in React using react-draggable

React Drag and drop tutorial; In this expeditious guide, you will find out the efficient approach on how to create or integrate the Drag and drop feature in React Js app using the react draggable npm library.

User experience is the key to success; every web and mobile application strives for better user engagement. It is made great by adding quintessential user interface components.

One such component is Drag and drop; It enhances user interaction, solves users’ problems. Ideally, it is a GUI element that, comparatively based on device gesture, a user chooses or gabs a virtual element, by the same token, drags it towards some other locus or on another element.

We will build the react Drag and drop component with the help of react draggable package. The React-Draggable is a popular and powerful library used to create a simple draggable component in react.

Create Drag and Drop Component in React

  • Step 1: Install New React Project
  • Step 2: Add React Draggable Pacakage
  • Step 3: Build React Draggable Component
  • Step 4: Add Events Callback Methods
  • Step 5: Get Draggable Position
  • Step 6: Axis Specific Dragging
  • Step 7: Start React App

Install New React Project

We assume you are starting from the absolute beginning, make sure to use the below command to install the new react app:

npx create-react-app react-drag-drop-demo

Move into the app folder:

cd react-drag-drop-demo

Add React Draggable Pacakage

The second instruction helps us to install React draggable package in react app.

npm install react-draggable

Build React Draggable Component

The Draggable class has to be imported from the ‘react-draggable’ package, and this class allows you to set up a new draggable element; even more, it gives you access to other important events that we will use in the next step.

You can use the Draggable directive to evoke the draggable element; you can move the current component within the viewport.

Open and update the src/App.js file.

import React from 'react';
import './App.css';
import Draggable from 'react-draggable';

class App extends React.Component {

  render() {
    return (
      <Draggable>
        <div className="draggableBlock">
          <div>Drag and Drop</div>
        </div>
      </Draggable>
    );
  }
}

export default App;

We defined the HTML div, and inside the draggable component, you can use this class to style the drag and drop component. Make sure to update the src/App.css file.

.draggableBlock {
  padding: 20px;
  background: rgb(80, 13, 235);
  width: 250px;
  cursor: move;
  color: wheat;
  text-align: center;
}

Add Events Callback Methods

The Draggable component comes with handy callback methods, we can tack the drag and drop position of the draggable element with onDrag(), onStart(), onStop(), onMouseUp(), onMouseDown(), onTouchStart() and onTouchEnd.

Here is how you can attach event handlers to the Draggable component and track the drag and drop element recklessly.

import React from 'react';
import './App.css';
import Draggable from 'react-draggable';

class App extends React.Component {

  handleEvent = (e, data) => {
    console.log('Event name: ', e.type);
    console.log(e, data);
  }

  render() {
    return (
      <Draggable
          onDrag={this.handleEvent}
          onStart={this.handleEvent}
          onStop={this.handleEvent}
          onMouseDown={this.handleEvent}
          onMouseUp={this.handleEvent}
          onTouchStart={this.handleEvent}
          onTouchEnd={this.handleEvent}>
        <div className="draggableBlock">
          <div>Drag and Drop</div>
        </div>
      </Draggable>
    );
  }
}

export default App;

Display Draggable Position

In this section, you will learn how to get and display the delta position, ideally the x-axis and y-axis; here is the code snippet that you can use to show the draggable element.

import React from 'react';
import './App.css';
import Draggable from 'react-draggable';

class App extends React.Component {

  state = {
    deltaAxis: {
      x: 0, 
      y: 0
    }
  };

  eventHanlder = (e, d) => {
    
    const { x, y } = this.state.deltaAxis;

    this.setState({
      deltaAxis: {
        x: x + d.deltaX,
        y: y + d.deltaY,
      }
    });
  };

  render() {

    const { deltaAxis } = this.state;

    return (
      <Draggable
        onDrag={this.eventHanlder}>

        <div className="draggableBlock">
          <strong>Axis Position:</strong>
          <div>
            <strong>x: {deltaAxis.x.toFixed(0)}, y: {deltaAxis.y.toFixed(0)}</strong>
          </div>
        </div>
      </Draggable>
    );
  }
}

export default App;

Axis Specific Dragging

You can use the axis property and set the draggable element to move towards a particular axis; yes, this can also be done; you can choose either x or y-axis.

import React from 'react';
import './App.css';
import Draggable from 'react-draggable';

class App extends React.Component {

  handleEvent = (e, data) => {
    console.log('Event name: ', e.type);
    console.log(e, data);
  }

  render() {
    return (
      <Draggable
          onDrag={this.handleEvent}
          axis="y"
         >
        <div className="draggableBlock">
          <div>Drag and Drop</div>
        </div>
      </Draggable>
    );
  }
}

export default App;

Start React App

Eventually, start the react app, consequently execute the given below command.

npm start

Copy the below url in the browser and hit enter to test the app.

http://localhost:3000

Conclusion

The react drag and drop example is over; this guide went through various methods to create a draggable component in the react app. Alongside, we learned to install and use the react-draggable plugin in react to build a drag and drop functionality and explored the various react-draggable events.