Implement Drag and Drop using React Component - GeeksforGeeks (2024)

Last Updated : 04 Apr, 2024

Improve

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 appropriate components and defining drag-and-drop behaviour using event handlers, you can enable users to interact with elements by dragging and dropping them across different parts of your application. In this tutorial, we will discuss how to implement drag-and-drop functionality using React components.

Output Preview: Let us have a look at how the final output will look likeImplement Drag and Drop using React Component - GeeksforGeeks (1)

Prerequisites:

  • Functional Components
  • JavaScript ES6
  • JSX

Steps to Create Application

Step 1: First, let’s create a new React application using Create React App. Open your terminal and run the following command:

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

Step 2: Next, install the React DnD library:

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

Project Structure:

Implement Drag and Drop using React Component - GeeksforGeeks (2)

Step 3: The updated dependencies in package.json file will look like:

"dependencies": {
"react": "^17.0.2",
"react-dnd": "^14.0.2",
"react-dnd-html5-backend": "^14.0.2",
}

Approach to implement Drag & Drop using React Component:

  • Wrap your application with a DndProvider from react-dnd to enable drag and drop functionality.
  • Define draggable items using the useDrag hook provided by react-dnd. This hook handles the drag behavior and provides the necessary properties like isDragging.
  • Create drop zones where items can be dropped. Use the useDrop hook to define drop behavior and handle the onDrop event to capture dropped items.
  • Use React’s useState hook to manage the state of dropped items. Update the state when an item is dropped or removed to reflect changes in the UI.
  • Apply CSS styles to visually indicate drag and drop interactions, such as changing opacity or border colors when dragging or hovering over drop zones.

Example: Implementing the Drag and Drop functionality. We’ll create two components: DragItem for draggable items and DropZone for drop zones.

JavaScript
//App.jsimport React, { useState } from 'react';import { DndProvider } from 'react-dnd';import { HTML5Backend } from 'react-dnd-html5-backend';import DragItem from './DragItem';import DropZone from './DropZone';const App = () => { const [droppedItems, setDroppedItems] = useState([]); const handleDrop = (item) => { setDroppedItems((prevItems) => [...prevItems, item]); }; const handleRemoveItem = (index) => { const updatedItems = [...droppedItems]; updatedItems.splice(index, 1); setDroppedItems(updatedItems); }; return ( <DndProvider backend={HTML5Backend}> <div style={{ display: 'flex', justifyContent: 'center', alignItems: 'center', height: '100vh' }}> <div style={{ border: '1px solid #ccc', padding: '20px', borderRadius: '5px' }}> <h1>Drag and Drop Example</h1> <div style={{ display: 'flex', justifyContent: 'space-around' }}> <div style={{ border: '1px solid #ccc', padding: '10px', borderRadius: '5px' }}> <h2>Drag Items</h2> <DragItem name="Item 1" /> <DragItem name="Item 2" /> <DragItem name="Item 3" /> </div> <div style={{ border: '1px solid #ccc', padding: '10px', borderRadius: '5px' }}> <h2>Drop Zone</h2> <DropZone onDrop={handleDrop} /> {droppedItems.map((item, index) => ( <div key={index} style={{ border: '1px solid #ccc', padding: '10px', borderRadius: '5px', marginTop: '10px', backgroundColor: 'lightblue', display: 'flex', justifyContent: 'space-between', alignItems: 'center', }}> <p>{item.name}</p> <button onClick={ () => handleRemoveItem(index)}> Remove </button> </div> ))} </div> </div> </div> </div> </DndProvider> );};export default App;
JavaScript
//DragItem.jsimport React from 'react';import { useDrag } from 'react-dnd';const DragItem = ({ name }) => { const [{ isDragging }, drag] = useDrag(() => ({ type: 'item', item: { name }, collect: (monitor) => ({ isDragging: monitor.isDragging(), }), })); return ( <div ref={drag} style={{ opacity: isDragging ? 0.5 : 1, cursor: 'move', border: '1px solid #ccc', padding: '10px', borderRadius: '5px', margin: '5px', backgroundColor: 'lightblue', }}> {name} </div> );};export default DragItem;
JavaScript
// DropZone.jsimport React from 'react';import { useDrop } from 'react-dnd';const DropZone = ({ onDrop }) => { const [{ isOver }, drop] = useDrop(() => ({ accept: 'item', drop: (item) => onDrop(item), collect: (monitor) => ({ isOver: monitor.isOver(), }), })); return ( <div ref={drop} style={{ border: `1px dashed ${isOver ? 'green' : 'black'}`, padding: '10px', }}> Drop here </div> );};export default DropZone;

Step to Run Application: Run the application using the following command from the root directory of the project

npm start

Output: Your project will be shown in the URL http://localhost:3000/

Implement Drag and Drop using React Component - GeeksforGeeks (3)

Note: After implementing the Drag and Drop functionality, you should be able to drag items from the DragItem component and drop them into the DropZone component. The dropped items should be rendered inside the DropZone.



Like Article

Suggest improvement

Next

Drag and Drop File Upload Component with React Hooks

Share your thoughts in the comments

Please Login to comment...

Implement Drag and Drop using React Component - GeeksforGeeks (2024)

FAQs

How to implement drag and drop feature for your React component? ›

Approach to implement Drag & Drop using React Component:

Create drop zones where items can be dropped. Use the useDrop hook to define drop behavior and handle the onDrop event to capture dropped items. Use React's useState hook to manage the state of dropped items.

How to make a draggable div in React? ›

The useDrag hook is a function that allows us to create draggable elements that can be moved around the screen. It accepts an object containing the specification of the type of draggable being generated, the item object representing the drag source, what props to collect and more.

What is the drag and drop area in React? ›

React DnD can make any element draggable and droppable. To achieve this, React DnD needs to have the references of all droppable items. All elements that are draggable and droppable need to be enclosed inside React DnD's context provider, which is used for initializing and managing the internal state.

How to implement drag and drop file upload in React? ›

To create the DragNDrop component and its associated CSS file, navigate to your project folder and create two new files called DragNDrop. jsx and drag-drop. css. Keep in mind that this article assumes you already have a ReactJS project set up, so we will not go over how to create a new project.

How do I create a drag and drop list in react JS? ›

The following steps describe how to configure this functionality:
  1. Enable item drag and drop. Set the itemDragging. ...
  2. Add the lists to the same group. Set the group property of both components to the same value to allow a user to drag and drop items between them.
  3. Reorder list items in code.

How to drag a component in React Native? ›

Creating a Draggable Component. After importing PanResponder class, you initiate it with . create method in componentWillMount() life cycle method. You could also write it in the constructor() .

How does react draggable work? ›

Draggable items are moved using CSS Transforms. This allows items to be dragged regardless of their current positioning (relative, absolute, or static). Elements can also be moved between drags without incident. If the item you are dragging already has a CSS Transform applied, it will be overwritten by <Draggable> .

What is the draggable function in react? ›

A module called React Draggable makes it simple to add incident-free drag movement to React elements and components. React Draggable package applies CSS changes to React components, making it easy and simple to drag components around a user interface (UI).

How do you make a component draggable in HTML? ›

To make an object draggable, set draggable=true on that element. Just about anything can be drag-enabled, including images, files, links, files, or any markup on your page. Here's the CSS for the container and box elements. The only CSS related to the drag feature is the cursor: move property.

How do you drag and drop between two lists in react? ›

To drag and drop an item or group of item between two list boxes can be achieved by setting allowDragAndDrop property as true and scope property should be set to both the list boxes.

How do you implement dropdown in React? ›

To create a dropdown in React, use a <select> element for options and an 'onChange' event to update state. Employ 'useState' for functional components or 'this. state' for class components.

How do you implement Dropzone in React? ›

Basic example

The useDropzone hook just binds the necessary handlers to create a drag 'n' drop zone. Use the getRootProps() fn to get the props required for drag 'n' drop and use them on any element. For click and keydown behavior, use the getInputProps() fn and use the returned props on an <input> .

Top Articles
Latest Posts
Article information

Author: Jerrold Considine

Last Updated:

Views: 5723

Rating: 4.8 / 5 (78 voted)

Reviews: 93% of readers found this page helpful

Author information

Name: Jerrold Considine

Birthday: 1993-11-03

Address: Suite 447 3463 Marybelle Circles, New Marlin, AL 20765

Phone: +5816749283868

Job: Sales Executive

Hobby: Air sports, Sand art, Electronics, LARPing, Baseball, Book restoration, Puzzles

Introduction: My name is Jerrold Considine, I am a combative, cheerful, encouraging, happy, enthusiastic, funny, kind person who loves writing and wants to share my knowledge and understanding with you.