How to use drag and drop in react js?
December 20, 2024Hi Friends 👋,
Welcome To aHoisting!
To use drag and drop in react js, you have to use onDragStart
, onDragOver
, onDrop
, and draggedItem
that’s you can use drag and drop in react js.
Today, I am going to show you, how to use drag and drop in react js.
Table of contents
- Install and create a new React app.
- Import react component.
- Create a Component.
Let’s start with the first step.
Step 1: Install and create a new React app.
First you have to install the React project. You should use create-react-app
command to create a new React project.
npx create-react-app my-app
cd my-app
npm start
Step 2: Import react component.
After installing, you have to import your React component.
import React, { useState } from "react";
Step 3: Create a Component.
You can use draggable
to use drag and drop in react js.
<div>
<h2>Drag and Drop Example</h2>
<ul>
{items.map((item, index) => (
<li
key={index}
draggable
onDragStart={(e) => onDragStart(e, index)}
onDragOver={(e) => onDragOver(e)}
onDrop={(e) => onDrop(e, index)}
style={{
padding: "8px",
margin: "4px",
border: "1px solid #ccc",
cursor: "move",
backgroundColor: "#f9f9f9",
}}
>
{item}
</li>
))}
</ul>
</div>
Use drag and drop example.
The below code is an example of a React. You have to import react
and use onDragStart
, onDragOver
, onDrop
, and draggedItem
to use drag and drop in react js.
App.js
import React, { useState } from "react";
const DragAndDrop = () => {
const [items, setItems] = useState(["Item 1", "Item 2", "Item 3", "Item 4"]);
const onDragStart = (e, index) => {
e.dataTransfer.setData("dragItemIndex", index);
};
const onDragOver = (e) => {
e.preventDefault(); // Allows drop
};
const onDrop = (e, index) => {
const dragItemIndex = e.dataTransfer.getData("dragItemIndex");
const newItems = [...items];
const draggedItem = newItems.splice(dragItemIndex, 1)[0];
newItems.splice(index, 0, draggedItem);
setItems(newItems);
};
return (
<div>
<h2>Drag and Drop Example</h2>
<ul>
{items.map((item, index) => (
<li
key={index}
draggable
onDragStart={(e) => onDragStart(e, index)}
onDragOver={(e) => onDragOver(e)}
onDrop={(e) => onDrop(e, index)}
style={{
padding: "8px",
margin: "4px",
border: "1px solid #ccc",
cursor: "move",
backgroundColor: "#f9f9f9",
}}
>
{item}
</li>
))}
</ul>
</div>
);
};
export default DragAndDrop;
In the above code example, I have used the draggable
to use drag and drop in react js.
Check the output of the above code.
All the best 👍