Building a Drag and Drop Interface with React Hooks
Last Updated :
24 Jul, 2024
Drag and Drop Interface feature is a simple React application that demonstrates the drag-and-drop functionality between two boxes. The boxes represent containers and items within them can be dragged and dropped from one box to another.
This interactive and user-friendly feature is commonly used in various web applications for tasks like organizing lists, sorting elements, or managing content.
Output Preview: Let us have a look at how the final feature will look like.
Final Project OutputApproach to create Drag and Drop Interface
We have two box and we are using useState hook to store the current state data of the box. Items are defined as a draggable and this items can be dragged from one box to another box through by using onDragStart, onDragOver and onDrop events. The main functionalities include:
- Dragging items from one box to another.
- Preventing the addition of duplicate items in the same box.
- Dynamically updating the state to reflect changes in each box.
Steps to Create Drag and Drop Feature using React Hooks
Step 1: Create a React application using the following command:
npx create-react-app gfg
Step 2: After creating your project folder(i.e. gfg), move to it by using the following command:
cd gfg
Step 3: Write the code mentioned in the example in App.js and App.css file respectively
Example: This below example demonstrate the Drag and Drop Interface with React Hooks
CSS
/* App.css */
/* Styling for container */
.container {
display: flex;
justify-content: center;
}
/* Styling for heading */
h1 {
text-align: center;
color: green;
}
/* Styling for Boxes */
.box {
border: 2px solid #333;
padding: 10px;
margin: 10px;
width: 250px;
height: 300px;
}
/* Styling for List Items */
ul {
list-style-type: none;
padding: 0;
}
li {
background-color: #f0f0f0;
border: 1px solid #ccc;
padding: 8px;
margin: 5px;
cursor: pointer;
}
li:hover {
background-color: #e0e0e0;
}
JavaScript
//File path: src/App.js
import React, { useState } from 'react';
import './App.css';
const App = () => {
// State for items in Box 1
const [box1Items, setBox1Items] = useState([
{ id: 1, text: 'Item 1' },
{ id: 2, text: 'Item 2' },
{ id: 3, text: 'Item 3' },
{ id: 4, text: 'Item 4' },
{ id: 5, text: 'Item 5' }
]);
// State for items in Box 2
const [box2Items, setBox2Items] = useState([]);
// Function to handle the start of a drag operation
const handleDragStart = (e, item) => {
// Set the data being dragged as
// text/plain with the serialized item
e.dataTransfer
.setData('text/plain', JSON.stringify(item));
};
// Function to handle the drag over event
const handleDragOver = (e) => {
// Prevent the default behavior to allow dropping
e.preventDefault();
};
// Function to handle the drop event
const handleDrop = (e, targetBox) => {
// Prevent the default behavior
// to avoid unwanted behavior
e.preventDefault();
// Parse the dropped item from the dataTransfer
const droppedItem = JSON.parse(
e.dataTransfer
.getData('text/plain')
);
// Check the target box and
// update the state accordingly
if (targetBox === 'box1') {
// Check if the same item is already present in Box 1
let isSameItemPresent = box1Items.some(
item => item.id === droppedItem.id
&& item.text === droppedItem.text
);
// Update the state of Box 1
// and remove the item from Box 2
setBox1Items((prevItems) =>
//If the same item is already present in Box 1 then
//again don't add that item
// else add the new item in Box 1
isSameItemPresent ?
[...prevItems] :
[...prevItems, droppedItem]
);
setBox2Items((prevItems) =>
//Remove the dragged item from Box 2
prevItems.filter(
(item) =>
item.id !== droppedItem.id
)
);
} else if (targetBox === 'box2') {
// Check if the same item is already present in Box 2
let isSameItemPresent = box2Items.some(
item => item.id === droppedItem.id
&& item.text === droppedItem.text
);
// Update the state of Box 2 and remove the item from Box 1
setBox2Items((prevItems) =>
//If the same item is already
// present in Box 2 then
//again don't add that item
// else add the new item in Box 2
isSameItemPresent ?
[...prevItems] :
[...prevItems, droppedItem]
);
setBox1Items((prevItems) =>
//Remove the dragged item from Box 1
prevItems.filter(
(item) =>
item.id !== droppedItem.id
)
);
}
};
return (
<>
<h1>
Drag and Drop Example
| GeeksForGeeks
</h1>
<div className="container" >
<div
className="box"
onDragOver={(e) => handleDragOver(e)}
onDrop={(e) => handleDrop(e, 'box1')}>
<h3>Box 1</h3>
<ul>
{box1Items.map((item) => (
<li
key={item.id}
draggable
onDragStart={
(e) =>
handleDragStart(e, item)
}>
{item.text}
</li>
))}
</ul>
</div>
<div
className="box"
onDragOver={(e) => handleDragOver(e)}
onDrop={(e) => handleDrop(e, 'box2')}>
<h3>Box 2</h3>
<ul>
{
box2Items.map((item) => (
<li
key={item.id}
draggable
onDragStart={
(e) =>
handleDragStart(e, item)
}>
{item.text}
</li>
))
}
</ul>
</div>
</div>
</>
);
};
export default App;
To run the application use the following command:
npm run start
Output: Now go to http://localhost:3000 in your browser:
Similar Reads
Building a Component Library with React Hooks and Storybook Building a component library is a powerful way to streamline the development process, ensure consistency across projects, and promote the reusability of UI elements. In this article, we'll explore how to create a component library using React Hooks and Storybook, a tool for developing UI components
3 min read
Drag and Drop File Upload Component with React Hooks In this article, we're going to delve into creating a drag-and-drop feature for uploading files using React Hooks. Dragging and dropping makes it simple for users to add files to a web app. With React Hooks we can control state and execute actions in components simplifying the management of drag and
4 min read
Form Handling with React Hooks Forms are an important part of web development. Form handling is a crucial user interaction for websites. React hooks provide a concise and very efficient way to handle the state of the form as the user interacts with the form fields. There are mainly two react hooks for this purpose. useState:- use
4 min read
Building a Tooltip Component with React Hooks Building a Tooltip Component with React Hooks is straightforward and effective. Tooltips are a common UI element used to provide additional information when a user hovers over or focuses on an element. In this article, we'll build a Tooltip component using React Hooks. PrerequisitesNPM & NodeJSR
3 min read
Building Custom Hooks Library in React Custom hooks in React allow developers to encapsulate and reuse logic, making it easier to manage state and side effects across multiple components. As applications become complex, developers often repeat similar patterns for state management, API calls, or event handling. This can lead to code dupl
4 min read
Sortable Drag and Drop with React and Tailwind CSS In this tutorial, we'll learn how to create a sortable drag-and-drop feature in a React application using Vite for quick and efficient development, along with Tailwind CSS for styling. This feature allows users to reorder items in a list by dragging and dropping them, enhancing the user experience o
3 min read
Implement Drag and Drop using React Component To add drag and drop functionality in your React application, you can use libraries like "react-beautiful-dnd" or "react-dnd". These libraries provide components and hooks that simplify the process of creating draggable and droppable elements in your UI. By wrapping your draggable items with the app
4 min read
Data Fetching Libraries and React Hooks Data fetching libraries like React Query and React Hooks simplify how developers fetch and manage data in React applications. These tools provide easy-to-use functions like 'useQuery' and 'SWR' that streamline API interactions and state management, improving code readability and reducing boilerplate
6 min read
Creating a Customizable Dashboard with React and Drag-and-Drop functionality In this article, we will create a Dashboard with a drag-and-drop functionality using React JS. This project basically implements useState principles and the use of vite to set up the run time environment of React and JavaScript. The drag and drop functionality will enable the user to drag from one c
4 min read
Drag and Drop List Using TypeScript A drag-and-drop sortable list in TypeScript lets users reorder items by dragging them to new positions. This is done using dragstart, dragend and dragover events for smooth DOM manipulation.What Weâre Going to CreateWeâll build a drag-and-drop sortable list with features like handling dragstart, dra
5 min read