What You'll Learn
- 1Explain why HTML5 drag events are a poor fit for touch, styling and insertion previews
- 2Assemble a sortable list from DndContext, sensors, SortableContext and useSortable
- 3Choose activation constraints and drag handles so clicks and touch scrolling still work
- 4Make a drag interaction operable from the keyboard and announced by a screen reader
Drag and drop looks like a weekend job and behaves like a project. The visual part is trivial: follow the pointer, translate a row, swap two items. Everything that makes the interaction feel correct lives somewhere else â telling a click apart from a drag, auto-scrolling when the pointer reaches the edge of a container, keeping a touch drag from swallowing a page scroll, letting a keyboard user reorder with arrow keys, and announcing that an item moved from position three to position seven. Native drag events give you almost none of that inside React, which is why most teams model dragging as pointer state handled by a library instead of as a markup attribute delegated to the browser.
Why native drag events disappoint
HTML5 drag and drop is built around a dragged element, not around an insertion point. You set a draggable attribute, stash something in the data transfer during dragstart, and hope a drop target reads it. Three things break immediately. The drag ghost is a browser-rendered snapshot you cannot style, so a card with a shadow and a badge turns into a flat rectangle. There is no way to know which gap the pointer is currently hovering, so every sortable list has to fake an insertion indicator with its own logic. And touch support is essentially absent: on mobile the same gesture is a long press that the browser reserves for text selection and context menus.
Pointer-based libraries invert the model. The element never actually drags; your component tracks pointer coordinates, applies a transform to a placeholder, and optionally renders a floating copy in an overlay. Because everything is normal React state, you can style the preview, show a live insertion line, cancel on escape, and render the same interaction for a keyboard sensor.
| Concern | Native HTML5 drag | Pointer-based library |
|---|---|---|
| Touch and long press | Conflicts with scrolling and selection | Own touch sensor with delay and tolerance |
| Drag preview | Unstyleable browser snapshot | Real element or overlay you control |
| Insertion feedback | Known only after the drop | Live index while hovering |
| Keyboard operation | Not provided | Sensor plus announcements |
| Scroll containers | Handled by the browser | Configurable auto-scroll |
| State during drag | Only what fits in dataTransfer | Ordinary React state |
The pieces a modern library separates
dnd-kit is useful because it names the concerns explicitly. The DndContext owns the event stream and is the only place that knows a drag is happening. Sensors decide how a drag starts: a pointer sensor for mouse and pen, a touch sensor for fingers, a keyboard sensor for arrow keys. Collision detection decides what sits under the pointer, ranging from pointer-within for exact hits to closest-centre for forgiving targets. SortableContext adds an ordering strategy, and useSortable combines a draggable row with a droppable slot so the list knows both what is moving and where it can land. Finally the DragOverlay renders a floating copy, which is what stops the surrounding rows from reflowing the moment a row lifts.
A sortable list with handles and stable ids
The list below keeps ordering in the parent through an onChange callback, uses a dedicated handle so text selection and buttons inside a row keep working, and reorders with arrayMove rather than mutating anything.
import { useState } from 'react';
import {
DndContext,
KeyboardSensor,
PointerSensor,
closestCenter,
useSensor,
useSensors,
} from '@dnd-kit/core';
import {
SortableContext,
arrayMove,
sortableKeyboardCoordinates,
useSortable,
verticalListSortingStrategy,
} from '@dnd-kit/sortable';
import { CSS } from '@dnd-kit/utilities';
function SortableRow({ id, label }) {
const { attributes, listeners, setNodeRef, transform, transition, isDragging } = useSortable({ id });
return (
<li
ref={setNodeRef}
className={isDragging ? 'row row-dragging' : 'row'}
style={{
transform: CSS.Transform.toString(transform),
transition,
}}
>
<button
type="button"
className="handle"
aria-label={'Reorder ' + label}
{...attributes}
{...listeners}
>
::
</button>
<span>{label}</span>
</li>
);
}
export function SortableList({ items, onChange }) {
const [activeId, setActiveId] = useState(null);
const sensors = useSensors(
useSensor(PointerSensor, { activationConstraint: { distance: 6 } }),
useSensor(KeyboardSensor, { coordinateGetter: sortableKeyboardCoordinates })
);
const handleDragEnd = ({ active, over }) => {
setActiveId(null);
if (!over || active.id === over.id) return;
const from = items.findIndex((item) => item.id === active.id);
const to = items.findIndex((item) => item.id === over.id);
onChange(arrayMove(items, from, to));
};
return (
<DndContext
sensors={sensors}
collisionDetection={closestCenter}
onDragStart={({ active }) => setActiveId(active.id)}
onDragOver={({ active }) => setActiveId(active.id)}
onDragEnd={handleDragEnd}
onDragCancel={() => setActiveId(null)}
>
<SortableContext
items={items.map((item) => item.id)}
strategy={verticalListSortingStrategy}
>
<ul className="list">
{items.map((item) => (
<SortableRow key={item.id} id={item.id} label={item.label} />
))}
</ul>
</SortableContext>
{activeId && <div className="hint">Release to drop</div>}
</DndContext>
);
}
Two details matter more than they look. The distance constraint of six pixels is what lets a click on the handle still count as a click, because the drag only begins once the pointer has moved past that threshold. And reordering by id rather than by position means the handler stays correct even when the list was filtered or sorted by something else in between renders.
Telling a click, a scroll and a drag apart
Every gesture conflict in a sortable list comes from the same place: pointer down means several things at once. On a mouse, a small movement threshold is enough. On a touch screen the same gesture is also how the user scrolls the page, so an immediate drag makes the list impossible to scroll, and no threshold saves you because a slow scroll also moves more than six pixels. The answer for touch is a delay: begin the drag only after the finger has stayed still for roughly two hundred milliseconds, then allow a small tolerance so a jittery finger does not cancel it.
import { PointerSensor, TouchSensor, useSensor, useSensors } from '@dnd-kit/core';
import { KeyboardSensor, sortableKeyboardCoordinates } from '@dnd-kit/sortable';
export function useListSensors() {
return useSensors(
useSensor(PointerSensor, { activationConstraint: { distance: 8 } }),
useSensor(TouchSensor, {
activationConstraint: { delay: 200, tolerance: 6 },
}),
useSensor(KeyboardSensor, { coordinateGetter: sortableKeyboardCoordinates })
);
}
Pair the touch sensor with a CSS rule of touch-action set to none on the handle element only, never on the list container. That single declaration tells the browser that once the gesture starts on the handle, scrolling is not its job. Applying it to the container instead makes the whole list undismissable on mobile, which is a bug that is easy to miss in a desktop test pass.
Keyboard operation and announcements
A drag that only works with a pointer excludes anyone who does not use one, and it is the interaction most likely to fail an audit. The keyboard sensor maps the same events onto keys: space or enter picks the row up, arrow keys move it, space drops it, escape cancels. dnd-kit keeps focus on the moved row as its position changes, so the user does not lose their place.
The other half is speech. Provide announcements describing what happened: picked up, moved over a position, dropped at a new position, cancelled. The default announcements cover English strings, but if your list has domain language such as lanes or swimlanes you should pass custom announcement handlers on the context rather than leaving the library to guess. Test with a screen reader once, because the failure mode is usually a missing live region rather than a wrong string.
Drop zones that are not part of the order
Not every target is a slot in the list. Trash bins, tag trays and file drop areas are droppables with an id and nothing to sort, and they resolve through the same collision detection. A droppable exposes an isOver flag through its ref callback, so the visual treatment is ordinary conditional markup: highlight while something valid hovers, reject what you do not accept, and act on drop.
import { useDroppable } from '@dnd-kit/core';
import { arrayMove } from '@dnd-kit/sortable';
function RemoveZone() {
const { isOver, setNodeRef } = useDroppable({
id: 'remove-zone',
data: { accepts: 'task' },
});
return (
<div ref={setNodeRef} className={isOver ? 'zone zone-active' : 'zone'}>
Drop here to remove
</div>
);
}
function handleDragEnd({ active, over }, tasks, setTasks) {
if (over && over.id === 'remove-zone') {
setTasks(tasks.filter((task) => task.id !== active.id));
return;
}
if (!over || active.id === over.id) return;
const from = tasks.findIndex((task) => task.id === active.id);
const to = tasks.findIndex((task) => task.id === over.id);
setTasks(arrayMove(tasks, from, to));
}
The same pattern scales to multiple containers, which is the subject of the advanced drag and drop lesson. The rule that keeps it manageable is that containers own their own droppable definition while the context owns the single event stream, so no container needs to know how many others exist.
Persisting an order without losing the user's place
Reordering is an optimistic operation. The list should move immediately and the server call happens after, because waiting for a round trip makes the interaction feel broken. Send the new order as an explicit array of ids rather than a from-and-to pair, since a single user gesture can move an item across several positions when the list is long. If the request fails, restore the previous array and show a message; the previous order is just the value you already had.
Guard against concurrent editors as well. Two people reordering the same list will produce two arrays that cannot both be right, so either version the order and reject stale writes or apply moves as operations against the current server state. A silent last-write-wins merge produces lists where items teleport, which users report as corruption rather than as a conflict.
Common Mistakes
Making the whole row draggable so links, checkboxes and text selection stop working
Fix: Put the listeners on a dedicated handle and leave the row content interactive
Applying touch-action none to the list container instead of the handle
Fix: Scope the rule to the handle so the list still scrolls on touch devices
Reordering by array index when the list may be filtered or sorted
Fix: Find positions by id and move with arrayMove so the intent survives other state
Showing a spinner until the server confirms the new order
Fix: Apply the order optimistically and roll back to the previous array on failure
Best Practices
- Give every draggable an accessible name and keep focus on the row while it moves
- Delay touch activation so scrolling and dragging do not fight for the same gesture
- Announce pick up, move and drop through the context announcement handlers
- Persist the full array of ids, not a source and destination index pair
Key Takeaways
- Native HTML5 drag gives no touch support, no styleable preview and no insertion index, which is why React apps use pointer-based libraries
- Sensors, collision detection and sorting strategies are separate concerns, and each one is swappable
- A drag handle plus an activation distance keeps clicks, selection and scrolling intact
- Keyboard sensors and spoken announcements are what make reordering accessible
- Optimistic reordering with rollback keeps the interface responsive without lying about server state