arrow-return

React: Building Interactive User Experiences with React DnD

4 min read

Share


Introduction

Drag-and-drop functionality enables users to manipulate elements on A React Project. To get started intuitively, let's set up a React project and integrate react-dnd into it. Follow the steps below:

Step 1: Create a new React Project

Open your terminal and run the following command:

#node 16
npx create-react-app dnd-project
cd dnd-project

Step 2: Install the react-dnd library and its dependencies

#[email protected]
#[email protected]
#[email protected]

npm install react-dnd @types/react-dnd react-dnd-html5-backend

Step 3: DraggableItem.js and DropZone.js

Open the project in your preferred code editor and navigate to the src directory. We will create two new components:

DraggableItem.js

import React from "react";
import { useDrag } from "react-dnd";

function DraggableItem({ name }) {
  const [{ isDragging }, drag] = useDrag({
    type: "item",
    item: { name },
    collect: (monitor) => ({
      isDragging: monitor.isDragging(),
    }),
  });

  return (
    <div ref={drag} style={{ opacity: isDragging ? 0.5 : 1 }}>
      Drag this
    </div>
  );
}

export default DraggableItem;

The DraggableItem component represents an item that can be dragged. By utilizing the useDrag hook from React-DND, we define the drag behavior of the draggable item. The item property specifies the type and ID of the item, while the collect function allows us to collect information about the drag state.

DropZone.js

import React from 'react';
import { useDrop } from 'react-dnd';

function DropZone({ onDrop }) {
  const [{ isOver }, drop] = useDrop({
    accept: 'item',
    drop: (item, monitor) => {
      onDrop(item);
    },
    collect: (monitor) => ({
      isOver: monitor.isOver(),
    }),
  });

  const backgroundColor = isOver ? 'lightgreen' : 'white';

  return (
    <div
      ref={drop}
      style={{ backgroundColor }}
      className="drop-zone"
    >
      {isOver ? 'Item Dropped!' : 'Drop Here'}
    </div>
  );
};

export default DropZone;

The DropZone component serves as the area where draggable items can be dropped. It uses the useDrop hook from React-DND to define the drop behavior of the drop zone. The accept property specifies the accepted item type, the drop function handles the dropped item, and the collect function provides information about the drop state.

Step 4: DndProvider Setup

Open the App.js file in the src directory and replace the existing code with the following:

import React, { useState } from "react";
import DraggableItem from "./DraggableItem";
import DropZone from "./DropZone";
import { DndProvider } from "react-dnd";
import { HTML5Backend } from "react-dnd-html5-backend";

const App = () => {
  const [droppedItem, setDroppedItem] = useState(null);

  const handleDrop = (item) => {
    setDroppedItem(item.name);
  };

  return (
    <DndProvider backend={HTML5Backend}>
      <div className="app">
        <h1>React DnD</h1>
        <div className="container">
          <div className="column">
            <h2>Draggable Items</h2>
            <DraggableItem name="Item 1" />
            <DraggableItem name="Item 2" />
            <DraggableItem name="Item 3" />
          </div>
          <div className="column">
            <h2>Drop Zone</h2>
            <DropZone onDrop={handleDrop} />
          </div>
        </div>
        <div className="result">
          {droppedItem && <p>Dropped item: {droppedItem}</p>}
        </div>
      </div>
    </DndProvider>
  );
};

export default App;

The DndProvider component is a crucial part of React-DND library that is responsible for setting up the drag-and-drop context within a React application. It acts as a wrapper component that establishes the necessary infrastructure for drag-and-drop functionality to work smoothly.

Step 5: Styling the Components

Finally, let's add some basic styles to our components. Open the App.css file in the src directory, and replace the existing code with the following:

.app { 
text-align: center;
padding: 20px;
}

.container {
display: flex;
justify-content: space-around;
}

.column {
flex: 1;
padding: 10px;
border: 1px solid gray;
}

.draggable-item {
cursor: move;
background-color: lightblue;
padding: 10px;
margin-bottom: 10px;
}

.drop-zone {
height: 150px;
border: 2px dashed gray;
display: flex;
justify-content: center;
align-items: center;
font-weight: bold;
font-size: 18px;
}

Step 6: Customize your components

Now with the basics for drag-and-drop components, you can improve usability with animations, colors, and styles however you like.

Conclusion

In summary, React-DND has been a valuable tool at Buzzvel, enabling us to incorporate seamless drag-and-drop interactions into our React applications. It has enhanced the user experience and made our interfaces more interactive and intuitive.