Skip to content
Tutorials Center
My learning

Topics

Lesson 76 of 132 ยท Advanced Patterns

Drag and Drop, Gestures and Pointer Events

Build drag and drop in React with HTML5 DnD and pointer events: a sortable list, swipe gestures, touch handling and accessible alternatives.

Dragging things around feels natural: move a card to another column, reorder a playlist, swipe a notification away, drop a file onto a page. Under the hood there are two separate toolkits in the browser, and choosing the right one is the most important decision in this lesson.

The HTML5 Drag and Drop API (draggable, onDragStart, onDrop) is built into the browser. It is little code for simple jobs, it knows how to drag files in from the desktop and text between windows, and it draws a "ghost" image for you. But it is awkward to style, it is poorly supported on touch screens, and it gives you almost no control over the movement. Pointer events (onPointerDown, onPointerMove, onPointerUp) are a lower-level tool: you receive raw positions from a mouse, a pen or a finger through one unified API, and you move things yourself. Almost every drag-and-drop library for sortable lists is built on pointer events for that reason.

This lesson uses both. You will move cards with HTML5 DnD, accept dropped files, drag a box with pointer capture, build a sortable list and a swipe-to-dismiss card by hand, and then look at what a library gives you and how to keep all of this accessible. Events in general are covered in Handling Events, and refs in Refs with useRef.

HTML5 drag and drop in React

The browser's model has three parts:

  1. A drag source is any element with draggable="true" (images, links and selected text are draggable by default). When the drag starts, dragstart fires, and you put data on event.dataTransfer.
  2. A drop target listens to dragover. By default the browser does not allow dropping on elements; you must call event.preventDefault() in onDragOver to say "yes, a drop is allowed here".
  3. When the user releases, drop fires on the target, and you read the data back from dataTransfer.

In React the events are onDragStart, onDragEnter, onDragOver, onDragLeave, onDrop and onDragEnd. The next example moves cards between two columns. The state holds which column each card is in; the drag only carries the card id.

Move cards between columns (HTML5 DnD)

Drag "Review quiz" over to "Done": the target gets a blue dashed border while you hover, and on release the card moves and the console prints Moved card b to done. Notice the design:

  • The state is the single source of truth. The drag handlers do not move DOM nodes; they only call setCards, and React re-renders the columns. This is the same idea as in Lifting State Up and Sharing State.
  • onDragLeave is tricky. It fires every time the pointer enters a child element of the column, which would make the highlight flicker. Checking event.currentTarget.contains(event.relatedTarget) ignores moves between children.
  • dataTransfer data is strings. Store an id, not the object, and look the card up in state. In dragover browsers hide the actual data for security, so you cannot read it before the drop; keep the "currently dragged id" in state or a ref if the hover feedback depends on it.

Dropping files

The same events accept files dragged from the desktop. The files arrive in event.dataTransfer.files. You must still call preventDefault() on dragover, or the browser navigates to the file when it is dropped.

A file drop zone

Drop a file from your file manager onto the box and it is listed with its size and type. Reading the content is a job for the FileReader/Blob APIs, covered with file inputs in Uncontrolled Forms, File Inputs and Complex Forms. A drop zone should never be the only way to upload: also provide a normal <input type="file">, which is keyboard and screen reader accessible.

HTML5 DnD has real limits. Touch screens: most mobile browsers do not start a drag from a finger touch without extra workarounds. Styling: you cannot style the ghost image much and cannot easily animate the other items. Control: you do not get continuous coordinates while dragging (on some browsers clientX/clientY are zero in dragend). For sortable lists, kanban boards and anything that must work on phones, use pointer events.

Pointer events: one API for mouse, touch and pen

Pointer events replaced the old pairs of mousedown/touchstart handlers. A single listener receives input from every device, and the event tells you which one it is:

Property Meaning
pointerType "mouse", "touch" or "pen"
pointerId Identifies one finger or device; multi-touch gives several ids
clientX, clientY Position relative to the viewport
buttons Bit mask of pressed buttons (1 is the primary button)
isPrimary true for the first contact of a given type

The drag recipe has four steps:

  1. onPointerDown: remember where the pointer started and call element.setPointerCapture(event.pointerId).
  2. While captured, every onPointerMove goes to your element even if the pointer leaves it. That is why you do not need window listeners.
  3. onPointerUp (and onPointerCancel): finish.
  4. Set touch-action: none in CSS on the draggable. Otherwise a finger drag scrolls the page instead, and the browser fires pointercancel.
Drag a box with pointer events

Drag the blue square: the coordinates under the area follow it, and it can never leave the grey area because of clamp. When you let go, the console logs the final position. Look at a few details:

  • Grab offset. We store clientX - position.x at pointer down, so the box does not jump to be centred under the cursor.
  • transform rather than left and top. Moving with translate avoids layout work (see Animation and Transitions).
  • The position lives in state, the "grab" lives in a ref. The offset is not drawn, so changing it should not cause a re-render.
  • Pointer capture guarantees that pointerup arrives at the box even when you release outside the grey area or the window.

On a phone, test with a real finger. Without touch-action: none the page scrolls under your drag. Put touch-action: pan-y on a horizontally swipeable item so vertical scrolling still works.

A sortable list by hand

A sortable list is the most common use of dragging. The trick that makes the list feel alive is to keep two ideas apart:

  • The committed order (state), which changes only when the drag ends.
  • The preview order, derived during the drag from where the pointer is.

To keep the math simple this example uses rows of a fixed height and absolute positioning. For a row at index i the top is i * ROW. While dragging, the dragged row follows the pointer exactly (startIndex * ROW + dy), and the preview index is that distance divided by the row height, rounded and clamped. All other rows take their preview positions, and a CSS transition slides them into place. Because the layout is derived, there is no DOM measuring at all.

Sortable list with pointer events

Grab the three-line handle and drag a row up or down: the row follows the pointer with a shadow, the others slide out of the way, and on release the status line says, for example, Bread moved to position 3 of 5. Three design decisions deserve attention:

  1. The handle, not the whole row, starts the drag. That leaves the buttons and any text inputs in the row usable. It also leaves page scrolling working when a finger touches the row outside the handle.
  2. Keys are the item values. The rows keep their identity while they change positions, so React moves existing elements instead of recreating them. See Reconciliation and Keys in Depth.
  3. Up and down buttons are not decoration. A drag with a pointer is impossible for keyboard and many screen reader users. The buttons offer the same operation, and the role="status" paragraph announces the result.

Real lists have rows with varying heights, scrolling containers, auto-scroll near the edges and nested lists. All of that is why most teams use a library for production sortables.

Gestures: swipe to dismiss

A gesture is a pattern recognised from a sequence of pointer events: swipe, long press, pinch, double tap. The recipe is to record, compare, and decide at pointer up. A swipe-to-dismiss card follows the finger horizontally and, if released beyond a threshold, flies off; otherwise it springs back.

Swipe to dismiss

Drag a card more than 100 pixels left or right and release: it disappears and the console prints Dismissed "Build finished" by right. A shorter drag snaps back because transition is only disabled while dragging. The card background turns red once you pass the threshold, giving feedback before you let go. Some details come from real-world gestures:

  • Thresholds beat exact positions. Humans do not drag precisely; a distance (or a velocity) threshold gives a forgiving result.
  • Velocity (distance over time between the last two moves) lets a quick short flick count as a swipe. Timestamps come from event.timeStamp.
  • Use touch-action carefully. pan-y tells the browser to handle vertical panning itself, while you receive horizontal moves.
  • Offer a button. The "Dismiss" button is the accessible alternative. It stops pointer-down propagation so pressing it does not start a swipe.
  • Handle pointercancel. The browser sends it when it takes over the gesture (for example, to scroll). Reset your state there, or the card stays stuck.

Gestures with several fingers (pinch to zoom) track several pointerId values in a ref map; this is where a library such as @use-gesture/react saves a lot of work.

Using a library

Hand-written pointer code is fine for one box or one simple list. For real products the details pile up: auto-scrolling, collision detection, nested containers, virtualized lists, drag overlays, screen reader announcements and keyboard sensors. Popular libraries (all read-only here, since the editor cannot install packages):

Library Notes
dnd-kit Modern hooks-based toolkit for React: sortable lists, grids, multiple containers, keyboard and touch sensors, accessibility announcements.
pragmatic-drag-and-drop Small, framework-independent core built on the native HTML5 API, used for boards and trees.
react-beautiful-dnd (and its successors) Older, list-focused library; check the maintenance status before starting a new project.
@use-gesture/react Gesture hooks (drag, pinch, scroll, hover) that give you deltas and velocity.

A sortable list with dnd-kit looks roughly like this (read-only, needs npm install @dnd-kit/core @dnd-kit/sortable):

JSX
import { DndContext, closestCenter, KeyboardSensor, PointerSensor, 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 }) {
  const { attributes, listeners, setNodeRef, transform, transition } = useSortable({ id });
  return (
    <li ref={setNodeRef} style={{ transform: CSS.Transform.toString(transform), transition }}>
      <button type="button" {...attributes} {...listeners}>Drag</button> {id}
    </li>
  );
}

function List({ items, setItems }) {
  const sensors = useSensors(
    useSensor(PointerSensor),
    useSensor(KeyboardSensor, { coordinateGetter: sortableKeyboardCoordinates })
  );

  function handleDragEnd({ active, over }) {
    if (over && active.id !== over.id) {
      setItems((current) => arrayMove(current, current.indexOf(active.id), current.indexOf(over.id)));
    }
  }

  return (
    <DndContext sensors={sensors} collisionDetection={closestCenter} onDragEnd={handleDragEnd}>
      <SortableContext items={items} strategy={verticalListSortingStrategy}>
        <ul>{items.map((id) => <SortableRow key={id} id={id} />)}</ul>
      </SortableContext>
    </DndContext>
  );
}

You can recognise our hand-written pieces: the preview order is SortableContext, the grab and pointer capture are PointerSensor, and the keyboard alternative is KeyboardSensor. The state stays yours; the library reports onDragEnd and you reorder an array with arrayMove, exactly like moveItem above.

Accessibility of drag and drop

Dragging is one of the least accessible interactions on the web, because it needs a pointing device and fine motor control. Follow these rules (the WCAG guideline is called "dragging movements"):

  1. Every drag must have a non-drag alternative: buttons to move up and down, a "Move to..." menu, or arrow keys on a focused handle. In our sortable example both buttons exist for that reason.
  2. Announce results. Use a role="status" live region ("Bread moved to position 3 of 5"). Libraries announce pick up, move and drop for you. See Accessibility in React.
  3. Make handles real controls. A focusable <button> with a clear label ("Reorder Bread") works better than an aria-hidden icon; we kept the icon decorative only because the buttons carry the function.
  4. Show focus and drop targets with something other than colour: borders, shapes, text.
  5. Make targets big enough. 24 CSS pixels is a minimum; 44 is friendlier for touch.
  6. Respect reduced motion for the sliding animation of other rows.
  7. Test with touch, a keyboard and a screen reader, not only a mouse.

Choosing an approach

Situation Use
Dropping files or text from outside the page HTML5 DnD (onDrop, dataTransfer)
Simple move between a few containers, desktop only HTML5 DnD
Sliders, resizable panes, draggable boxes, canvases Pointer events with pointer capture
Sortable lists, boards, grids, touch devices Pointer events or a library such as dnd-kit
Swipes, pinch, long press Pointer events or @use-gesture/react

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Why must a drop target call event.preventDefault() in onDragOver?

    By default most elements are not valid drop targets. Cancelling dragover tells the browser a drop is allowed here, so that the drop event fires. For files it also prevents the browser from opening the dropped file.
  2. 2. What does setPointerCapture do in a pointer-based drag?

    With capture, pointermove and pointerup keep arriving at your element until the pointer is released, so you need no window-level listeners and a fast drag does not lose the element.
  3. 3. A horizontal swipe card should still let the user scroll the page vertically with a finger. Which CSS helps?

    pan-y leaves vertical panning to the browser while your handlers receive the horizontal movement. touch-action none disables all browser panning on the element, which is right for a free-moving box but not for a swipe card inside a scrolling page.
  4. 4. In the sortable list example, why is the committed order only updated on pointer up?

    While dragging, the layout is computed from the drag state (start index and distance). Committing once avoids reordering the underlying data on every pointer move and gives a clean cancel path.
  5. 5. Which is the best accessible alternative to dragging rows in a list?

    Dragging needs a pointer and motor precision. A non-drag way to do the same operation, announced to assistive technology, makes the feature usable for everyone.

Summary

  • HTML5 drag and drop (draggable, onDragStart, onDragOver, onDrop) is the right tool for dropping files and simple desktop moves; remember preventDefault() on dragover and keep your own state as the source of truth.
  • Pointer events unify mouse, touch and pen. Use setPointerCapture, touch-action, and handle pointerup and pointercancel.
  • Keep committed state separate from the preview computed during the drag; store transient grab data in refs.
  • Gestures such as swipe are thresholds and velocity measured over a sequence of pointer events.
  • For production sortables and boards, use a library (dnd-kit, pragmatic-drag-and-drop, @use-gesture/react).
  • Every drag interaction needs a keyboard-friendly, screen-reader-announced alternative.

Next: Internationalization