What You'll Learn
- 1Restructure state so a card move is a pure operation over containers
- 2Wire drag start, drag over and drag end so live reordering and final drops agree
- 3Choose a collision detection strategy that works for empty and uneven containers
- 4Persist a cross-container move optimistically with a rollback that restores order
Reordering one list is a solved problem. Moving a card between columns is a different exercise, because a single gesture now spans two containers and two kinds of position: which column the card left, which column it entered, and where in that column it landed. Most implementations fail on the edges â an empty column that will not accept a drop, a card that jumps back for a frame before settling, a drag that works with a mouse and dies on a phone â and almost all of them come from the same root cause: the state shape was designed for one list and then stretched to hold several.
Make the move a pure function first
Before touching drag events, decide what a move is. Given the current columns, the card id, the target column and the target index, produce a new set of columns with the card removed from its old home and inserted at the new position, without mutating anything. This function is testable without a browser, it is the same function the optimistic update and the rollback both call, and it forces you to answer the awkward questions â what happens when the card is dropped where it started, when the target index is beyond the end, when two cards share an id â while you are still thinking about data rather than pixels.
import { useState } from 'react';
import {
DndContext,
DragOverlay,
PointerSensor,
TouchSensor,
closestCorners,
useSensor,
useSensors,
} from '@dnd-kit/core';
import { SortableContext, verticalListSortingStrategy } from '@dnd-kit/sortable';
export function KanbanBoard({ columns, onMove }) {
const [activeCard, setActiveCard] = useState(null);
const sensors = useSensors(
useSensor(PointerSensor, { activationConstraint: { distance: 6 } }),
useSensor(TouchSensor, { activationConstraint: { delay: 180, tolerance: 8 } })
);
const handleDragStart = ({ active }) => {
const column = columns.find((item) => item.id === active.data.current.columnId);
const card = column.cards.find((item) => item.id === active.id);
setActiveCard(card);
};
const handleDragOver = ({ active, over }) => {
if (!over) return;
const sourceId = active.data.current.columnId;
const targetId = over.data.current && over.data.current.columnId
? over.data.current.columnId
: over.id;
if (sourceId === targetId) return;
onMove(active.id, { from: sourceId, to: targetId, index: null }, { live: true });
};
const handleDragEnd = ({ active, over }) => {
setActiveCard(null);
if (!over) return;
const targetId = over.data.current && over.data.current.columnId
? over.data.current.columnId
: over.id;
onMove(active.id, { to: targetId }, { live: false });
};
return (
<DndContext
sensors={sensors}
collisionDetection={closestCorners}
onDragStart={handleDragStart}
onDragOver={handleDragOver}
onDragEnd={handleDragEnd}
>
<div className="board">
{columns.map((column) => (
<section key={column.id} data-column-id={column.id} className="column">
<h2>{column.title}</h2>
<SortableContext
items={column.cards.map((card) => card.id)}
strategy={verticalListSortingStrategy}
>
<div className="column-body">
{column.cards.map((card) => (
<SortableCard key={card.id} card={card} columnId={column.id} />
))}
</div>
</SortableContext>
</section>
))}
</div>
<DragOverlay>{activeCard ? <CardGhost card={activeCard} /> : null}</DragOverlay>
</DndContext>
);
}
The split between dragOver and dragEnd is the part people get wrong. Dragging across columns must move the card while the pointer is still down, otherwise the card stays in the source column until release and the user cannot see where it will land. But a live move on every over event means your state is being rewritten dozens of times per second, so the handler has to be cheap and idempotent â moving the same card to the same column repeatedly must be a no-op, which the guard in the middle of the function ensures.
Collision detection decides what counts as a target
Collision detection answers one question: given the pointer and every droppable, which one did the user mean? The choice matters more in a board than in a list, because columns have different widths, cards have different heights, and an empty column contains no card geometry for the pointer to overlap.
| Strategy | Picks | Good for | Weak spot |
|---|---|---|---|
| Pointer within | The droppable under the cursor | Precise targets, file drop zones | Empty space inside a column is a miss |
| Closest centre | Nearest centre point | Small targets, menus | Drifts with uneven column sizes |
| Closest corners | Nearest edge pair | Kanban columns and lists | Sensitive to very tall cards |
| Rectangle intersection | Largest overlapping area | Grids and free-form canvases | Costlier, ambiguous with nesting |
| Intersection with shape | Custom shape match | Drawing tools and maps | You must supply the geometry |
Closest corners is the practical default for boards because it measures the distance to the rectangle edges rather than the centre, so a card dragged into the top of a wide column still resolves to that column instead of drifting towards its neighbour. Whichever you choose, give the column itself a droppable definition with an id equal to the column id, so a column can receive a drop even when it has no cards to hover.
The overlay exists so the layout does not lie
When a card is dragged by transforming the original node, the hole it leaves behind is still part of layout â the column collapses, the cards below jump up, and the drop target you were aiming at has moved. The overlay pattern fixes this by leaving the original in place, dimmed or hidden, and rendering a floating copy that follows the pointer. Layout stays stable for the whole gesture, and the copy can carry a shadow and a rotation that would otherwise trigger layout if applied to the real node.
Two details complete the effect. Give the overlay a fixed width taken from the source so it does not resize to the pointer position, and add a slight delay before it appears when the drag is fast, which reads as the card being lifted rather than teleporting. The original node should keep its space with opacity rather than display none, because removing it from flow is exactly the jump you were trying to avoid.
Persisting without lying about the server
A cross-container move is one user intent, so it should be one request: card id, target column, target index, and a version of the board so the server can reject a stale write. Apply it optimistically with the same pure function, remember the previous columns, and on failure restore them with a message. What you should not do is send one request per intermediate dragOver event; those are previews, and only the final position is intent.
import { useCallback, useRef, useState } from 'react';
export function useBoard(initialColumns, saveMove) {
const [columns, setColumns] = useState(initialColumns);
const [error, setError] = useState(null);
const liveRef = useRef(initialColumns);
const gestureRef = useRef(null);
const move = useCallback(
(cardId, target, options) => {
if (!gestureRef.current) gestureRef.current = liveRef.current;
const next = applyMove(liveRef.current, cardId, target);
liveRef.current = next;
setColumns(next);
if (options.live) return;
const baseline = gestureRef.current;
gestureRef.current = null;
saveMove({ cardId, target, version: next.version }).catch((failure) => {
setError(failure.message);
liveRef.current = baseline;
setColumns(baseline);
});
},
[saveMove]
);
return { columns, move, error };
}
Keep the baseline snapshot for exactly one gesture: capture it on the first live move, use it only if the write fails, and drop it the moment the request is issued so a later drag can never restore a board from two interactions ago. Version numbers matter on a board that more than one person edits: without them, two users moving cards in different columns produce two arrays that both look valid on their own screens and contradict each other once either reloads.
Touch, autoscroll and boards that exceed the viewport
On a phone, a board is almost always wider than the screen, which means the drag gesture competes with horizontal panning as well as with the vertical scroll of a column. Delay activation for touch so a scroll never starts a drag, set touch-action on the card handle only, and configure auto-scroll so the board pans when the pointer reaches an edge. Autoscroll is where most mobile implementations fail: without it, a card can only be dropped in whatever columns happen to be visible, and the user has no way to reach the rest of the board while holding a card.
Long boards also need a decision about where the column headers live. Sticky headers that stay during scroll are helpful but they create an overlay that steals drops near the top of a column, so the droppable area must extend past the visible header rather than stopping at its edge.
Strategies for the other shapes
Vertical lists use a vertical strategy and grids use a rectangle one, but boards often contain a second shape: a horizontal row of chips inside a column, or a cover-image strip. Mixing shapes means giving each SortableContext the strategy that matches its axis and making sure the collision detection can distinguish them â usually by scoping the active droppable to the container the pointer is inside before refining to a card.
If you find yourself fighting geometry for more than an afternoon, the signal is usually that the interaction needs a different affordance. Alternatives such as a move menu, a keyboard shortcut or an explicit column picker serve the same intent without pixel-precision, and for accessibility they are not a fallback: they are the primary path that keyboard and switch users depend on while the pointer gesture is the shortcut.
Common Mistakes
Moving a card only on drag end so the board does not respond while dragging
Fix: Apply live moves during dragOver and treat dragEnd as the point to persist
Relying on pointer-within detection so empty columns reject drops
Fix: Register each column as a droppable and use closest corners for resolution
Sending a server request for every intermediate move during a drag
Fix: Batch to one request carrying card, target column, index and board version
Deleting the dragged card from layout so every target shifts underneath the pointer
Fix: Keep the source in place and render a floating copy in a drag overlay
Best Practices
- Write the move as a pure function shared by the live preview, the persistence call and the rollback
- Give columns their own droppable ids so empty and full columns behave identically
- Delay touch activation and enable auto-scroll so boards work on small screens
- Version the board so concurrent edits are rejected rather than silently merged
- Provide a non-drag path to the same action for keyboard and assistive technology users
Key Takeaways
- Multi-container dragging is a state problem first: define move as a pure operation before wiring events
- DragOver drives the live preview while dragEnd is where intent is persisted
- Collision detection determines whether empty columns and uneven layouts work at all
- Overlays keep layout stable so drop targets do not move mid-gesture
- Optimistic moves need a snapshot, a rollback and a version check to survive failures and conflicts