Simple Drag and Drop in React without an external library.

Shahid Yousafxai
Nerd For Tech
Published in
3 min readMar 13, 2023

--

Drag and Drop in React

What is Drag and Drop in React?

Drag and drop is a way of moving or manipulating elements on a screen using a mouse or touchpad. It’s perfect for reordering a list of items or moving items from one list to another. You can build drag-and-drop components in React in a very simple way.
Let’s build a drag-and-drop in your react app where you have some sort of list or table and you want to change the order of your list or table rows by following these steps.

1. Make the elements draggable.

All we need to do here is to pass the “draggable” prop to each list item or table row which makes the elements draggable.

Drag and Drop Code Snippet

Now you can drag every element/row in the list/table. (Note: You can just Drag the elements)

2. Get the element that we are dragging.

We’ll use the useRef hook to hold the item we’re dragging, then we’ll use the “onDragStart” method to drag and paste it to another element in this list.

Drag and Drop Code Snippet

dragItem.current = e.target.id dragItem.current is now holding the element which we are dragging.

3. Get the element on which we are hovering or on which the element will be replaced.

In this step, we need to find which element our dragged element is floating on. With UseRef we can achieve this, the “onDragEnter” event listener will also do this.

Drag and Drop Code Snippet

dragOverItem.current = e.currentTarget.iddragOverItem.current” is now holding the element on which we are hovering or on which the element will be replaced.

(Note: Please make sure this time you declare “e.currentTarget.id” not “e.target.id” otherwise it wouldn’t work).

4. Replace the draggable item with other to rearrange.

One of the last steps is to rearrange the list when you manage to place the element you dragged on top of another element or in another place. We can achieve it by using the “onDragEnd” method.

Drag and Drop Code Snippet

Enjoy your Drag and Drop.

--

--

Shahid Yousafxai
Nerd For Tech

Software Engineer | Frontend Developer | Technical Writer