Femil Patodiya
Written By Femil Patodiya ReactJS Developer

Drag-and-Drop in React: A Step-by-Step Guide React DND

post date
February 7, 2024
Drag-and-Drop in React_ A Step-by-Step Guide for React DND
Reading Time: 5 minutes

Understanding React DnD

React DnD stands out as a robust library, streamlining the integration of drag-and-drop functionality into React applications effortlessly. By handling the intricacies under the hood, React DnD empowers developers to concentrate on crafting interactive and user-friendly interfaces with ease.

React Beautiful DnD, an intuitive drag-and-drop library by Atlassian, streamlines UI interaction. Atlassian, known for Jira, pioneer in Agile tools.

Key Concepts and Terminology

To maximize the potential of React DnD, grasping fundamental concepts and terminology is crucial:

Drag Sources

Drag sources, encapsulating draggable components, enable user-initiated movement. React DnD enhances these elements with drag-specific features and behaviors. By specifying a drag source component, developers can define what can be dragged and its appearance during the dragging process.

Drop Targets

Drop targets are components that define valid places where drag sources can be dropped. When a drag source hovers over a drop target, React DnD furnishes the essential props and methods for managing the drop action. These elements can evaluate and either accept or reject the dropped item according to tailored criteria, granting precise management of drag-and-drop functionality.

Drag-n-Drop Context

The drag-and-drop context is a shared object that holds information about the ongoing drag-and-drop operations within a specific component tree. It allows components to access information about the dragged item, and the source and target components, and provides methods to interact with the drag-and-drop system.

React DnD work Behind the Scenes

React DnD work behind the scenes

Enhancing the interaction between the DOM and React-DnD

Let’s explore how React-DnD communicates between the DOM (Document Object Model) and itself. React-DnD is closely linked with the HTML Drag and Drop API and provides different implementations, called backends, for browsers to handle events like touch and mouse actions. In our example, we’ll use the standard HTML5 backend.

When you drag something on the screen, it’s not just a regular part of the webpage but an object called an “item.” Each item is like a simple JavaScript object that contains information about what’s being dragged. To control where you can drop this item, you need to define its type, like saying it’s a “card.”

Monitors play a vital role in keeping track of the drag-and-drop process. They help update component properties based on changes in the drag-and-drop state. Essentially, monitors monitor each object’s state – whether it’s currently being dragged, if something is hovering over it, or if an item was recently dropped onto it.

Enhancing the interaction between the React-DnD and React

Now, let’s talk about the second part of this communication process. After a drag-and-drop event shares information with React-DnD, the library seamlessly passes this data to React. This transmission is crucial for updating components, managing state changes, or interfacing with an external database.

Developers can create a Collector function, allowing each component to monitor the drag-and-drop state. This function efficiently gathers relevant information from the monitors, ensuring components stay in sync with ongoing drag-and-drop interactions.

Using this mechanism, we can convey updated values like “highlighted” and “hovered” as props to the component where the collector is defined.

Moving on to Drag Sources and Drop Targets, a drag source represents the draggable component carrying information needed to perform a specific action at the drop target. On the other hand, the drop target serves as a container that selectively accepts specific types of drag sources. Once accepted, the drop target triggers and executes the specified action.

Getting Started with React DnD

To integrate React DnD into your React project, follow these straightforward steps:

Installation and Setup

Begin by installing React Dnd along with its HTML5 backend through the following process:

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

Once installed, it will be helpful to familiarize yourself with the way React DnD works as a “middle-man” between React and the DOM as shown in the above figure.

Configuration and Setup

Dnd Provider Setup

The Main component in this code is like the starting point. It brings in the React DnD library, using the HTML5 backend to handle drag-and-drop actions. Inside it, the App component is enclosed, forming a smooth environment for crafting interactive user interfaces with drag-and-drop capabilities.

For configuring and establishing drag sources and drop targets within React DnD, adhere to these outlined directives:

Drag Sources

1. Import the necessary components from react-dnd:

import { useDrag } from 'react-dnd';

2. The useDrag hook serves as a tool enabling the creation of draggable entities that facilitate screen movement. It takes in an object delineating the type of draggable being produced, the item object embodying the drag source, the gathered props, and additional specifications.

Drop Targets

1. Import the necessary components from react-dnd:

import { useDrop } from 'react-dnd';

2. The useDrop hook is a function used in conjunction with the useDrag hook, it allows you to create drop targets that can accept items that are being dragged by the users on the screen. It additionally accepts an object outlining the specifics regarding the type of data items accepted by the drop target, the collected props, and other pertinent details.

Implementing fundamental drag-and-drop functionality with the HTML5 Backend

React DnD offers support for multiple backends, among which is the HTML5 backend, serving as the default option for contemporary web browsers. Let’s delve into incorporating fundamental drag-and-drop capabilities using the HTML5 backend.

Dragging a Component

To enable the dragging behavior for a component, you simply need to enclose it within the DragSource component.

To make any component draggable, first of all we create a DraggableItem component and encapsulate it with the useDrag hook offered by React DnD. The useDrag hook requires an options object, allowing you to designate the type of the dragged item. Additionally, you can include a collect function to gather details about the drag state, such as determining whether the component is presently undergoing a drag operation.

Dropping a Component

To enable dropping behavior for a component, you need to wrap it with the DropTarget component.

To make any component droppable, first of all we introduce a DropTargetComponent, enclosed within the useDrop hook. This hook requires an options object where you can define the accepted types of items (accept) and a drop callback function responsible for handling the dropped item. Additionally, the collect function gathers information about the drop state, including whether an item is presently being hovered over the component.

Real-world Example

  1. Building a Kanban Board with Draggable Cards
  2. Creating a File Uploader with drag-and-drop Support
  3. Designing a Dashboard with Customizable Widgets
  4. Developing a Drag-and-Drop Quiz Builder
  5. Developing a Chess Board Game

Conclusion

In this guide, we explored how React DnD works, dealing with things like Drag Sources and Drop Targets. It’s like setting up a cool feature in a game where you can drag and drop items. We even peeked behind the scenes, seeing how React DnD talks between the webpage and the React code. The guide helps you get started, making it sound like setting up a new game level. There’s a real-world example too, like building a cool drag-and-drop menu for a game. So, if you want to make your website or game more interactive, React DnD is your secret weapon for creating awesome stuff!

If you want to check out the code and give it a spin yourself, head over to the GitHub repo called react-dnd github for a live demo, you can play around with the app on this link: live-demo.

Femil Patodiya
Written By Femil Patodiya ReactJS Developer

Popular Categories

Get In Touch

Contact
GET IN TOUCH

Consult With Our Experts Today!

Your Benefits!

  • Professional Project Consultation
  • Detailed Project Proposal
Skype Skype Whatsapp WhatsApp