Mastering React JS Drag and Drop: A Comprehensive Tutorial

Mastering React JS Drag and Drop: A Comprehensive Tutorial


  • Share on Pinterest

Introduction to React Drag and Drop

ReactJS Drag and Drop is a popular technique used to create interactive web applications. It allows users to move elements around the screen using a mouse or touch interface. The drag-and-drop functionality can be useful for tasks such as rearranging items in a to-do list or organizing files in a document management system.

To implement drag-and-drop functionality in React, we need to set up our React environment and install the necessary libraries. This article will guide you through the steps to set up the environment, install libraries, and create draggable and droppable components.

Setting Up the React Environment

Before we start building our drag-and-drop functionality, we need to set up our React environment. Here are the steps you need to follow:

  1. Install Node.js from the official website
  2. Open your terminal or command prompt and navigate to the directory where you want to create your React project.
  3. Run the following command to create a new React project:
npx create-vite-app my-app --template react-ts

Installing and Importing Libraries

In order to implement drag-and-drop functionality in React, we need to install the following libraries: react-dndreact-dnd-html5-backend, and styled-components, typescript, @types/styled-components

These libraries provide the necessary components and APIs to enable drag and drop.

  1. Open your terminal or command prompt and navigate to your project directory.
  2. Run the following command to install the required libraries:
npm install --save react-dnd react-dnd-html5-backend @types/react-dnd @types/react-dnd-html5-backend
  1. Once the installation is complete, we need to import the necessary components in our code. Open the file where you want to implement drag and drop (e.g App.tsx) and add the following imports:
import { DndProvider } from 'react-dnd'; 
import { HTML5Backend } from 'react-dnd-html5-backend';

Creating a Draggable Component

Now that we have our environment set up and the necessary libraries installed and imported, we can start building our drag-and-drop functionality.

Let’s create a simple draggable component that can be moved around the screen. Here’s the code:

import { useDrag } from "react-dnd";
import { StyledDraggable } from "./Styled";
import { ItemI } from "../types";

const Draggable: React.FC<ItemI> = ({ label }) => {
  const [{ isDragging }, drag] = useDrag(() => ({
    type: "box",
    item: { type: "box", label },
    collect: (monitor) => ({
      isDragging: !!monitor.isDragging()
    })
  }));

  return (
    <StyledDraggable ref={drag} style={{ opacity: isDragging ? 0.5 : 1 }}>
      {label}
    </StyledDraggable>
  );
};

export default Draggable;

Let’s break down this code:

  1. We define an interface for our props, which in this case only has a label property.
  2. We use the styled-components library to define our draggable component. This component has a gray border, some padding, and a cursor style that indicates it can be moved.
  3. We define our draggable component using the useDrag hook, which is provided by the react-dnd library. This hook returns an array with two values: an object with information about the drag operation, and a ref that we need to attach to the element we want to make draggable.
  4. Inside the useDrag hook, we define the type of item being dragged (in this case, a ‘box’), and a collect function that returns information about the drag operation, such as whether it’s currently in progress or not.
  5. We pass the drag ref to our StyledDraggable component, which makes it draggable.

Creating a Droppable Component

Now that we have a draggable component, we need to create a droppable component where we can drop it. Let’s create a simple droppable component that changes color when a draggable item is dropped on it. Here’s the code:

import { useDrop } from "react-dnd";
import { StyledDroppable } from "./Styled";
import { DroppableI } from "./types";

const Droppable: React.FC<DroppableI> = ({ onDrop, droppedBox }) => {
  const [{ isOver }, drop] = useDrop(() => ({
    accept: "box",
    drop: (item, monitor) => {
      onDrop(item);
    },
    collect: (monitor) => {
      return {
        isOver: !!monitor.isOver()
      };
    }
  }));

  return (
    <StyledDroppable ref={drop} isOver={isOver}>
      {droppedBox}
    </StyledDroppable>
  );
};

export default Droppable;

Let’s break down this code:

  1. We use styled-components to define our droppable component. This component has a gray dashed border, some padding, and a border radius to make it look like a drop zone.
  2. We define our droppable component using the useDrop hook, which is also provided by the react-dnd library. This hook returns an array with two values: an object with information about the drop operation, and a ref that we need to attach to the element we want to make droppable.
  3. Inside the useDrop hook, we define the type of item that can be dropped on this component (in this case, a ‘box’) and a collect function that returns information about the drop operation, such as whether there is currently a draggable item hovering over it or not.
  4. We pass the drop ref to our StyledDroppable component, which makes it droppable.

Handling Drag and Drop Events

Now that we have both a draggable and a droppable component, we need to handle the events that occur when a draggable item is dropped on the droppable component. Let’s add some event-handling code to our App component:

import { useState } from "react";
import { DndProvider } from "react-dnd";
import { HTML5Backend } from "react-dnd-html5-backend";

import Draggable from "./components/Draggable";
import Droppable from "./components/Droppable";
import { GridContainer, Item, FourthItem } from "./Styled";
import { BoxT, ItemI } from "./types";

const App: React.FC = () => {
  const [droppedBox, setDroppedBox] = useState<BoxT>(
    "Waiting to drop something..."
  );

  const handleDrop = (item: ItemI) => {
    setDroppedBox(item.label);
  };

  return (
    <DndProvider backend={HTML5Backend}>
      <GridContainer>
        <Item>
          <Draggable label="Box 1" />
        </Item>
        <Item>
          <Draggable label="Box 2" />
        </Item>
        <Item>
          <Droppable onDrop={handleDrop} droppedBox={droppedBox} />
        </Item>
        <FourthItem>
          <div>Drop here!</div>
        </FourthItem>
      </GridContainer>
    </DndProvider>
  );
};

export default App;

Let’s break down this code:

  1. We import useState from the react package to keep track of the dropped box.
  2. We import the DndProvider component from the react-dnd library and the HTML5Backend backend.
  3. We import the Draggable and Droppable components that we created earlier.
  4. We define a GridContainer component using styled-components that displays our draggable and droppable components side by side.
  5. We define the App component, which uses useState to keep track of the dropped box.
  6. We define a handleDrop function that sets the droppedBox state to the label of the dropped item. We also pass the droppedBox value to the Dropabble component in order to be rendered if it has value
  7. We wrap our GridContainer component inside the DndProvider component, passing in the HTML5Backend backend.
  8. We render our draggable components, passing in a label prop to each.

Summary

In this tutorial, we learned how to use react-dnd to implement drag-and-drop functionality in a React application. We started by installing the necessary packages and setting up a basic project structure. Then we created a draggable component using the useDrag hook and a droppable component using the useDrop hook. Finally, we handled drag-and-drop events using the onDrop prop.

ReactJS Drag and Drop is a powerful user interface pattern that can greatly enhance the user experience of your application. By using react-dnd, we can easily add drag-and-drop functionality to our React components and create more intuitive and interactive user interfaces.

Takeaways

  • The react-dnd library provides a simple and powerful way to add drag-and-drop functionality to your React components.
  • The useDrag and useDrop hooks are used to make components draggable and droppable, respectively.
  • The onDrop prop can be used to handle drag-and-drop events.
  • ReactJS Drag and Drop can greatly enhance the user experience of your application.

You can find a live demo of this example in the following link. Also, the source code is available in this GitHub repository.

Happy coding!

LET’S KEEP IN TOUCH!

We’d love to keep you updated with our latest news and offers 😎

We don’t spam! Read our privacy policy for more info.