Drag and drop experiences are often built to sort lists of content vertically OR horizontally.

react-beautiful-dnd is an excellent tool to implement drag and drop functionalities in our applications. React beautiful dnd is an open-source library that allows web developers to easily integrate drag-and-drop functionality into their applications. It is currently the most popular drag-and-drop library in the React world.

Final Result:

react-beautiful-dnd

Let’s get started

Step 01Installing react-beautiful-dnd npm package:

npm i react-beautiful-dnd

Step 02 – Implementing react beautiful dnd:

Head over to your component where you want to implement (dnd) I have the design all ready. here’s the source code snippet for my listing where I am going to implement (dnd).

<Paper sx={{ marginBottom: "10px" }}>
<ListItem>
   <ListItemAvatar>
     <Avatar src="/user.png"/>
   </ListItemAvatar>
 <ListItemText primary="Lunch" secondary="Basit" />
</ListItem>
</Paper>

So after the design next we need to import the following things from react-beautiful-dnd. copy and paste this at the top of your component


import {DragDropContext,Draggable,Droppable} from "react-beautiful-dnd";

Next Wraps the part of your application in <DragDropContext> your Content here </DragDropContext> you want to have drag and drop enabled for. e.g

<Container maxWidth="sm">
<DragDropContext>
<List sx={{ width: "100%", maxWidth: 360, bgcolor: "background.paper" }}>
  {itemData.map((item, index) => {
    return (
        <Paper
        key={item.id}
        elevation={2}
        sx={{ marginBottom: "10px" }}
        >
        <ListItem>
        <ListItemAvatar>
            <Avatar src={item.img} />
        </ListItemAvatar>
        <ListItemText primary={item.title} secondary={`Author: ${item.author}`} />
        </ListItem>
        </Paper>
    );
   })}
</List>
</DragDropContext>
</Container>

Next is to import <Droppable/> Droppable is an area that can be dropped into and it Contains over items that we want to drag and drop. So go ahead and move everything inside DragDropContext into Droppable component function with an argument provided and then we need to pass two things to our Div i.e {…provided.droppableProps} and ref={provided.innerRef} e.g

<Droppable droppableId="list">
{(provided) => (
<List
    {...provided.droppableProps}
    ref={provided.innerRef}
    sx={{ width: "100%", maxWidth: 360, bgcolor: "background.paper" }}
>
{itemData.map((item, index) => {
    return (
        <Paper elevation={2} sx={{ marginBottom: "10px" }}>
            <ListItem>
                <ListItemAvatar>
                    <Avatar src={item.img} />
                </ListItemAvatar>
                <ListItemText primary={item.title} secondary={`Author: ${item.author}`} />
            </ListItem>
        </Paper>   
    );
    })}
</List>
)}
</Droppable>

We need to pass an Id to the Droppable component droppableId which must be a string in this tutorial it’s a list but it could be anything it’s totally up to you.

The Next final thing is to Import Draggable

Draggable is – What can be dragged around

So inside this component, our item will exist that we want to drag around

So go ahead and Import Draggable into your component and wrap the content that you want to drag around into the Draggable component i.e

{itemData.map((item, index) => {
return (
<Draggable key={item.id} draggableId={item.id.toString()} index={index}>
    {(provided) => (
    <Paper
        ref={provided.innerRef}
        {...provided.draggableProps}
        {...provided.dragHandleProps}
        elevation={2}
        sx={{ marginBottom: "10px" }}
    >
        <ListItem>
            <ListItemAvatar>
                <Avatar src={item.img} />
            </ListItemAvatar>
            <ListItemText primary={item.title} secondary={`Author: ${item.author}`} />
        </ListItem>
    </Paper>
    )}
</Draggable>
);
})}

We need to pass draggableId prop to the Draggable Component in my case I have an integer in my array of objects which I am mapping so I need to write toString() to convert that integer id to a string but if you guys have already a string then no need to type toString().

Next, we need to pass three more props to our component

ref={provided.innerRef}, {…provided.draggableProps} and {…provided.dragHandleProps}

The final step is to update our array whenever we will drag and drop an item somewhere we need to update the array with updated indexes of items.

so in order to do that, we need to pass a function to DragDropContext onDragEnd

<DragDropContext onDragEnd={handleDragEnd}>

const handleDragEnd = (result) => {
		if (!result.destination) return;
		const items = Array.from(data);
		const [reorderedItem] = items.splice(result.source.index, 1);
		items.splice(result.destination.index, 0, reorderedItem);

		setData(items);
	};

I have an array inside our react hook so the first step is to get an array from the hook then we need to reorder that record and then update our hook/array with an updated record

That’s it

If you liked it Please do like, comment, share, and Subscribe to our Youtube Channel