Create React Draggable Component with react-draggable Package

Last updated on by Digamber

This React 16+ tutorial walks you through on creating and implementing drag and drop feature in the React component using the react-draggable library.

Theoretically, User Experience is one of the most crucial aspects of modern-day web and mobile applications. Drag and drop is one of the UI elements that allow users to choose and move HTML elements within the application layout. In this tutorial we are going to focus only on drag part and will cover drop feature later.

It makes the human-computer interaction more intuitive; we can implement the draggable element functionality in React application. So, let’s start building react draggable functionality.

For the react draggable example, we need to create a React JS application. In this application, we will check how to work with React event handlers to keep an eye on user action.

Create a New React Project

npx create-react-app react-draggable-tutorial

Get into the react application root.

cd react-draggable-tutorial

Install React Draggable Module

React draggable is a popular component; it offers a simple solution for building component’s elements draggable.

Execute command to install the react-draggable package.

npm i react-draggable

Creating React Draggable Component

In this step, we are raising the curtains from the secret of making a React component draggable. Well, this is not tough, though.

To add, the drag functionality in the component is simple. You need to import the Draggable service from from ‘react-draggable’ package.

Using a draggable element is easy; you need to declare the <Draggable> </Draggable> tag. Within the draggable directive, you need to specify the collection of elements that need to be dragged within the layout.

So, wrap the HTML element around the Draggable directive to enable the dragging within the layout.

// App.js
import React from 'react';
import './App.css';

import Draggable from 'react-draggable';

class App extends React.Component {

  render() {
    return (
      <Draggable>
        <div className="drag-wrapper">
          <div>You can drag me now.</div>
        </div>
      </Draggable>
    );
  }
}

export default App;

Give some styling through CSS to draggable element, add the code in App.css.

.drag-wrapper {
  width: 200px;
  cursor: move;
  padding: 50px;
  text-align: center;  
  background: #e5e5e5;  
}

Start your application and see the draggable component in action:

npm start

Create React Draggable Component with react-draggable Package

Events of React Draggable

Draggable components support callback methods and have almost every event to deal with any type of situation. Here is the events and callback methods list that i am going to enumerate for the draggable component.

  • onStart: This is called when dragging event invokes.
  • onDrag: Invoked when the drag event is in process.
  • onStop: This event evokes when dragging ends.
  • onMouseUp: This is event is evoked when the mouse is moved before stoping the drag.
  • onMouseDown: Called when the mouse is clicked to begin drag.
  • onTouchEnd: This is called in touch state before the drag ends.
  • onTouchStart: Invoked in touch condition before drag begins.

Implement Events in React Draggable

We have discussed the react draggable events and callbacks in the previous step, now its time to bring those events in action. So, we are adding events in the Draggable React component.

// App.js

import React from 'react';
import './App.css';

import Draggable from 'react-draggable';

class App extends React.Component {

  eventControl = (event, info) => {
    console.log('Event name: ', event.type);
    console.log(event, info);
  }

  render() {
    return (
      <Draggable
          onDrag={this.eventControl}
          onStart={this.eventControl}
          onStop={this.eventControl}
          onMouseDown={this.eventControl}
          onMouseUp={this.eventControl}
          onTouchStart={this.eventControl}
          onTouchEnd={this.eventControl}>
        <div className="drag-wrapper">
          <div>You can drag me now.</div>
        </div>
      </Draggable>
    );
  }
}

export default App;

You will see the similar output in the browser:

Implement Events in React Draggable

Define Axis in Draggable Component

Generally, sometimes you may need to identify in which direction the draggable element is moved. Guess what, it could be solved with axis property. It affects specifically flushing to the DOM.

You can go with x, y, and both value, whereas both is the default value.

The below examples explains how to vertically drag the draggable component with axis prop.

// App.js
import React from 'react';
import './App.css';

import Draggable from 'react-draggable';

class App extends React.Component {
  render() {
    return (
      <Draggable
          axis="y"
        >
        <div className="drag-wrapper">
          <div>You can drag me vertically.</div>
        </div>
      </Draggable>
    );
  }
}

export default App;

Find React Draggable Element Position

// App.js
import React from 'react';
import './App.css';

import Draggable from 'react-draggable';

class App extends React.Component {

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

  handleDrag = (e, d) => {
    const { x, y } = this.state.deltaXyPos;
    this.setState({
      deltaXyPos: {
        x: x + d.deltaX,
        y: y + d.deltaY,
      }
    });
  };

  render() {

    const { deltaXyPos } = this.state;

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

        <div className="drag-wrapper">
          <p>Drag position:</p>
          <div>
            <strong>x: {deltaXyPos.x.toFixed(0)}, </strong>
            <strong>y: {deltaXyPos.y.toFixed(0)}</strong>
          </div>
        </div>
        
      </Draggable>
    );
  }
}

export default App;

You can see the below screenshot to find out the final result:

Find React Draggable Element Position

The Bottom Line

So this was it, we have completed the React draggable tutorial. In this tutorial, we learned how to create a draggable component in React application. I hope it will give you some mere idea about dragging functionality to React.