Implementing Drag and Drop in React.js: A Step-by-Step Guide

Implementing Drag and Drop in React.js: A Step-by-Step Guide

Implementing Drag and Drop in React.js: A Step-by-Step Guide

Feb 14, 2025

Drag-and-drop functionality is a fundamental interaction model that enhances the usability and interactivity of modern web applications. Users are increasingly familiar with this feature in a variety of contexts, such as organizing content, uploading files, or rearranging items within a list or task management application. As web applications grow in complexity, developers need robust tools and libraries that can handle these interactions efficiently, and React.js—being a leading frontend framework—has several solutions to implement such features.

Among the various libraries available for React, react-dnd stands out due to its flexibility, extensibility, and active community support. Unlike other drag-and-drop libraries, react-dnd is not just a simple plug-and-play solution but a comprehensive library designed for building complex drag-and-drop interactions, such as sortable lists, custom drag previews, or even complex multi-component interfaces. This makes it ideal for developers who need full control over the drag-and-drop behavior while maintaining the performance and scalability of their applications. 

In this blog, we will explore how to build a robust drag-and-drop feature in React using the react-dnd library. We will cover everything from setting up the environment to implementing a working example with proper explanations and code snippets. 

Why Use Drag and Drop in React?

Implementing drag-and-drop functionality enhances the user experience by making interfaces more interactive. Some common use cases include:

  • File Uploads: Dragging files into an upload box.

  • Kanban Boards: Moving tasks between different stages.

  • Custom Sorting: Rearranging lists or items.

  • Interactive Dashboards: Allowing users to reposition widgets.

  • E-commerce Applications: Allowing users to customize their shopping cart by dragging and dropping items.

Since React manages state efficiently, using a library like react-dnd ensures a smooth and responsive drag-and-drop experience.

Setting Up the React Environment

Before we dive into the implementation, let’s set up a React project and install the necessary dependencies.

Step 1: Create a New React App

If you haven't already set up a React app, you can create one using:

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

Step 2: Install Dependencies

For implementing drag-and-drop, we will use react-dnd and react-dnd-html5-backend. Install them using:

npm install react-dnd react-dnd-html5-backend

Now that we have our environment set up, let’s move on to implementing drag-and-drop functionality.

Understanding react-dnd

react-dnd is a powerful library that simplifies drag-and-drop interactions in React. It follows the Drag Source and Drop Target model:

  • Drag Source: The element that will be dragged.

  • Drop Target: The element where the dragged item can be dropped.

To use react-dnd, we need to wrap our application with a DndProvider and specify an appropriate backend.

Implementing Drag-and-Drop in React

Step 1: Wrap the App in DndProvider

Modify index.js to include DndProvider:

import React from 'react';
import ReactDOM from 'react-dom';
import { DndProvider } from 'react-dnd';
import { HTML5Backend } from 'react-dnd-html5-backend';
import App from './App';
ReactDOM.render(
  <DndProvider backend={HTML5Backend}>
    <App />
  </DndProvider>,
  document.getElementById('root')
);

Step 2: Create a Draggable Item Component

Now, let's create a DraggableItem.js component:

import React from 'react';
import { useDrag } from 'react-dnd';
const DraggableItem = ({ name }) => {
  const [{ isDragging }, drag] = useDrag(() => ({
    type: 'ITEM',
    item: { name },
    collect: (monitor) => ({
      isDragging: !!monitor.isDragging()
    })
  }));
  return (
    <div ref={drag} style={{
      padding: '10px',
      margin: '5px',
      backgroundColor: isDragging ? 'lightgrey' : 'white',
      border: '1px solid black',
      cursor: 'grab'
    }}>
      {name}
    </div>
  );
};
export default DraggableItem;

Step 3: Create a Drop Target Component

Now, let’s create a DropTarget.js component where the draggable items can be dropped:

import React from 'react';
import { useDrop } from 'react-dnd';
const DropTarget = ({ onDrop }) => {
  const [{ isOver }, drop] = useDrop(() => ({
    accept: 'ITEM',
    drop: (item) => onDrop(item.name),
    collect: (monitor) => ({
      isOver: !!monitor.isOver()
    })
  }));
  return (
    <div ref={drop} style={{
      width: '200px',
      height: '200px',
      backgroundColor: isOver ? 'lightgreen' : 'lightblue',
      border: '2px dashed black',
      display: 'flex',
      alignItems: 'center',
      justifyContent: 'center'
    }}>
      Drop Here
    </div>
  );
};
export default DropTarget;

Step 4: Combine Everything in App.js

Now, modify App.js to use both DraggableItem and DropTarget:

import React, { useState } from 'react';
import DraggableItem from './DraggableItem';
import DropTarget from './DropTarget';
const App = () => {
  const [droppedItem, setDroppedItem] = useState(null);
  return (
    <div style={{ display: 'flex', justifyContent: 'space-around', padding: '20px' }}>
      <div>
        <h3>Draggable Items</h3>
        <DraggableItem name="Item 1" />
        <DraggableItem name="Item 2" />
        <DraggableItem name="Item 3" />
      </div>
      
      <DropTarget onDrop={(item) => setDroppedItem(item)} />
      
      {droppedItem && (
        <div>
          <h3>Dropped Item</h3>
          <p>{droppedItem}</p>
        </div>
      )}
    </div>
  );
};
export default App;

Conclusion

Congratulations! You have successfully implemented drag-and-drop functionality in a React app using react-dnd. Building on this foundation, you can develop ever more advanced drag-and-drop applications: to reorder a list, build dashboards, or, if you like, implement file uploads. Go ahead and play some with various features, depending on what use you want to make of them! 

Superflex.ai simplifies the coding process through AI-powered Figma to React workflow. It is easily integrated into VS Code and  enables cleaner, faster code with less effort.

Ready to Transform Your Workflow? Visit Superflex.ai and revolutionize the way you build front-end applications.