Member-only story
How to use Native Drag and Drop in React
There are many good DnD libraries one could use with React, and we won’t be building another one. Instead, we will implement a small app to move elements from one list to another (aka trello clone). Why? There are two reasons:
- To learn how to work with drag and drop. And what is a better way of learning if not getting our hands dirty?
- It is fun
So let’s dive in.
Create A New React App
Every tutorial starts with running npx create-react-app my-app --template typescrypt
and ours is not an exception. Run the command and clear the default files.
DnD Container
Creating reusable components is a good practice. Creating reusable components that can be dragged around even better. To achieve that we want our component to be agnostic of what it renders but still provide the dragging functionality. For example, it can look like this:
<DndContainer
key={list.id}
id={list.id}
onMove={handleMove}
>
<TrelloList list={list} />
</DndContainer>
Here we have a TrelloList
which is passed to aDndContainer
as a child. When dragging is finished handleMove
is invoked as a callback.
Let’s create a new components
folder and dnd-container/dnd-container.tsx
inside.
What do we want the component to do? We want it to make everything we pass into it draggable. How can we do it? By cloning…