Drag sorting Ant Design Table with dnd kit
- Introduction
- Prepare dummy data
- Define a state variable for drag overlay
- Convert
Table
into sortable preset of dnd kit - DraggableWrapper
- DraggableRow
- handleDragStart
- handleDragEnd
Introduction
I was trying to implement Drag sorting with handler for Ant Design Table. I found that react-sortable-hoc is not going to be enhancement further and the author encourages to use dnd kit. This article summarizes what I did to implement it with dnd kit.
Prepare dummy data
1 | function App() { |
The important thing here is that the key used to identify an item must be truthy value. I struggled with a situation that the first item is not draggable. After some minutes of debugging, I found that if the key is falsy value, it is not draggable. But I couldn’t find the root cause for this.
Define a state variable for drag overlay
1 | // ID to render overlay. |
activeId
will be used for determining whether to render drag overlay or not.
Convert Table
into sortable preset of dnd kit
1 | const sensors = useSensors( |
According to sortable single container, enclose Table
in DndContext
, wrap body (tbody
) with SortableContext
and implement useSortable
in row (tr
). In this example, DraggableWrapper
implements SortableContext
and DraggableRow
implements tr
with useSortrable
.
DragOverlay
is rendered only when activeId
has a valid ID value.
DraggableWrapper
1 | function DraggableWrapper(props: any) { |
DraggableWrapper
implements SortableContext
. items
shall be a list of keys to identify items, not items themselves. Inside tbody
, children
is a list of rows and each item will invoke Table.components.body.row
, which is DraggableRow
.
DraggableRow
1 | function DraggableRow(props: any) { |
DraggableRow
implements tr
with useSortable
, where id
must be the same with a key
of each item. We want to make a row draggable, so assign setNodRef
to tr
. And we want to enable dragging only when a user grabs a drag handle, so assign listeners
to td
containing a drag handle.
handleDragStart
1 | function handleDragStart(event: any) { |
handleDragEnd
1 | function handleDragEnd(event: any) { |
handleDragEnd
performs swapping two items. Here, to find indexes of two items in data source, we need to compare key
of an item and id
of useSortable
.
You can find demo here.