Table of contents
1.
Introduction
2.
Prerequisites
3.
Approach to Use React Draggable
4.
Steps to Create React Application and Installing Module
4.1.
Step 1: Create a React App
4.2.
Step 2: Install React Draggable
4.3.
Step 3: Using React Draggable in a Component
4.3.1.
Example 1: Basic Draggable Component
4.4.
Step 4: Adding Constraints
4.4.1.
Example 2: Restricting Movement Within a Parent Element
4.5.
Step 5: Handling Drag Events
4.5.1.
Example 3: Tracking Position Changes
5.
Make Each Card Draggable
5.1.
Import the Draggable Component
5.2.
Create a Draggable Card Component
5.3.
Add Some Basic Styling
5.4.
Using the Draggable Card
6.
Adding a Drag Handle to the Cards
6.1.
Modify the Card Component
6.2.
Update the Styling
6.3.
Using the Modified Draggable Card
7.
Frequently Asked Questions
7.1.
How do I install React Draggable?
7.2.
How do I restrict a draggable component within a specific area?
7.3.
Can I track the position of a draggable element?
8.
Conclusion
Last Updated: Feb 2, 2025
Medium

How to use react-draggable module in React JS

Author Sinki Kumari
0 upvote
Career growth poll
Do you think IIT Guwahati certified course can help you in your career?

Introduction

The react-draggable module in React.js allows developers to create draggable UI components with ease. It is commonly used for building interactive elements like modals, cards, and custom drag-and-drop features. This module simplifies event handling, making user interactions smoother.

How to use react-draggable module in React JS

In this article, you will learn about the react-draggable module, its syntax, key features, and how to implement it effectively in your React.js applications.

Prerequisites

Before using React Draggable, you should have:

  • Basic knowledge of React.js
     
  • Node.js and npm installed on your system
     
  • A working React project or the ability to create one

Approach to Use React Draggable

To implement React Draggable in your project, follow these steps:

  1. Install React Draggable: Add the package to your project.
     
  2. Import React Draggable: Include it in your component.
     
  3. Wrap Elements with Draggable Component: Make elements draggable.
     
  4. Customize Behavior: Use props to control movement and constraints.
     
  5. Handle Events: Implement drag event handlers.

Steps to Create React Application and Installing Module

Step 1: Create a React App

If you don’t have a React app set up, create one using the following command:

npx create-react-app react-draggable-demo
cd react-draggable-demo

Step 2: Install React Draggable

Use npm to install the react-draggable package:

npm install react-draggable

Step 3: Using React Draggable in a Component

Now, create a component and use React Draggable to make an element draggable.

Example 1: Basic Draggable Component

import React from "react";

import Draggable from "react-draggable";
const DraggableBox = () => {
  return (
    <Draggable>
      <div style={{ width: "200px", padding: "20px", background: "lightblue", textAlign: "center", cursor: "move" }}>
        Drag Me!
      </div>
    </Draggable>
  );
};


export default DraggableBox;


Explanation:

  • The Draggable component wraps around a div.
     
  • The div has styling to indicate it is draggable
    .
  • Users can click and drag the box anywhere in the viewport.

Step 4: Adding Constraints

You may want to limit the draggable area to prevent elements from going out of bounds.

Example 2: Restricting Movement Within a Parent Element

import React from "react";
import Draggable from "react-draggable";
const DraggableWithinBounds = () => {
  return (
    <div style={{ width: "400px", height: "400px", border: "2px solid black", position: "relative" }}>
      <Draggable bounds="parent">
        <div style={{ width: "150px", padding: "15px", background: "lightcoral", textAlign: "center", cursor: "move" }}>
          Drag Me Within Box!
        </div>
      </Draggable>
    </div>
  );
};
export default DraggableWithinBounds;


Explanation:

  • The Draggable component has the bounds prop set to parent, restricting movement within the parent div.
     
  • The element stays within the black-bordered box when dragged.

Step 5: Handling Drag Events

You can track the position of a draggable element using event handlers.

Example 3: Tracking Position Changes

import React, { useState } from "react";
import Draggable from "react-draggable";
const DraggableWithPosition = () => {
  const [position, setPosition] = useState({ x: 0, y: 0 });
  const handleDrag = (e, data) => {
    setPosition({ x: data.x, y: data.y });
  };
  return (
    <div>
      <p>Current Position: X: {position.x}, Y: {position.y}</p>
      <Draggable onDrag={handleDrag}>
        <div style={{ width: "150px", padding: "15px", background: "lightgreen", textAlign: "center", cursor: "move" }}>
          Drag Me & Track Position!
        </div>
      </Draggable>
    </div>
  );
};
export default DraggableWithPosition;


Explanation:

  • The onDrag event updates the position state.
     
  • The current X and Y coordinates are displayed dynamically.

Make Each Card Draggable

To make elements draggable in React, we need to use a library that helps us handle the dragging functionality. One popular library for this is react-draggable. First, let's install the library. Open your terminal and run the following command:

npm install react-draggable


Once the library is installed, we can start using it in our React components. Let's create a simple card component and make it draggable. Here’s how you can do it:

Import the Draggable Component

In your React file, import the Draggable component from the react-draggable library.

import React from 'react';
import Draggable from 'react-draggable';

Create a Draggable Card Component

Now, let’s create a card component and wrap it with the Draggable component. This will make the card draggable.

function DraggableCard() {
    return (
        <Draggable>
            <div className="card">
                <h2>Drag me around!</h2>
                <p>This is a draggable card.</p>
            </div>
        </Draggable>
    );
}


export default DraggableCard;

Add Some Basic Styling

To make the card look better, let’s add some basic CSS. Create a styles.css file and add the following styles:

.card {
    width: 200px;
    padding: 20px;
    border: 1px solid #ccc;
    border-radius: 8px;
    background-color: #f9f9f9;
    box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
    cursor: grab;
}


Make sure to import this CSS file in your React component:

import './styles.css';

Using the Draggable Card

Finally, use the DraggableCard component in your main application file, such as App.js.

import React from 'react';
import DraggableCard from './DraggableCard';

function App() {
    return (
        <div className="App">
            <h1>React Draggable Example</h1>
            <DraggableCard />
        </div>
    );
}
export default App;


By following these steps, you have created a draggable card in React. The Draggable component from the react-draggable library makes it easy to add dragging functionality to any element.

Adding a Drag Handle to the Cards

Sometimes, you might want to limit the dragging functionality to a specific part of the card, like a handle. This can be useful for improving the user experience. Let's see how to add a drag handle to our card.

Modify the Card Component

First, we need to modify our DraggableCard component to include a handle. We'll add a handle element inside the card and specify it as the drag handle.

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


function DraggableCard() {
    return (
        <Draggable handle=".handle">
            <div className="card">
                <div className="handle" style={{ cursor: 'grab', padding: '10px', backgroundColor: '#ddd' }}>
                    Drag from here
                </div>
                <h2>Drag me around!</h2>
                <p>This is a draggable card with a handle.</p>
            </div>
        </Draggable>
    );
}
export default DraggableCard;

Update the Styling

Let's update the CSS to make the handle more visible. Modify the styles.css file as follows:

.card {
    width: 200px;
    padding: 20px;
    border: 1px solid #ccc;
    border-radius: 8px;
    background-color: #f9f9f9;
    box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.handle {
    cursor: grab;
    padding: 10px;
    background-color: #ddd;
    text-align: center;
    border-bottom: 1px solid #ccc;
}

Using the Modified Draggable Card

The DraggableCard component is now ready with a drag handle. You can use it in your main application file just like before.

import React from 'react';
import DraggableCard from './DraggableCard';
function App() {
    return (
        <div className="App">
            <h1>React Draggable Example with Handle</h1>
            <DraggableCard />
        </div>
    );
}
export default App;


By specifying the handle prop in the Draggable component, we limit the dragging functionality to the element with the class handle. This makes the card draggable only when you click and drag from the handle area.

Frequently Asked Questions

How do I install React Draggable?

You can install React Draggable using npm:

npm install react-draggable

How do I restrict a draggable component within a specific area?

Use the bounds prop and set it to parent or specify dimensions. Example:

<Draggable bounds="parent">...</Draggable>

Can I track the position of a draggable element?

Yes, use the onDrag event to update and display position values.

Conclusion

React Draggable is a powerful tool for adding drag-and-drop functionality to React applications. In this article, we covered installation, implementation, and customization of draggable components with examples. By using event handlers and constraints, you can build interactive UI elements effortlessly.

Live masterclass