AI summary

Build a drag-to-scroll container in React with Pointer Capture and a 5 px threshold, so letting go after a drag doesn't click the buttons inside.

  • The new scroll position is the starting scroll minus how far the mouse moved.
  • Pointer Capture removes the need for listeners on document.
  • Tell a click from a drag by distance, not by time.

A horizontal list of cards scrolls easily with a finger on a touch screen. With a mouse you have to go and grab the scrollbar. Drag to scroll fixes that, and it comes down to two small ideas: move the scroll by however far the mouse moved, and don’t mistake a drag for a click.

When the mouse goes down, save where it is and where the scroll is. scrollLeft is how many pixels the container is scrolled from its left edge. As the mouse moves, the new value is scrollLeft = startScrollLeft - dx, where dx is how far the mouse has traveled since the press.

The subtraction looks backwards at first. When you pull the cards left, you reveal what’s further right, so scrollLeft goes up.

Mouse movement and scrollLeftExample values: starting scrollLeft of 300, maximum of 800 pixels.
  1. Mouse movement (dx): -200 px

    You pulled left. 300 - (-200) = 500.

    • scrollLeft500 / 800 px
  2. Mouse movement (dx): 0 px

    The mouse hasn't moved. The value is where it started.

    • scrollLeft300 / 800 px
  3. Mouse movement (dx): +200 px

    You pulled right. 300 - 200 = 100.

    • scrollLeft100 / 800 px
  4. Mouse movement (dx): +400 px

    The math gives -100 and the browser clamps it to 0. You don't have to check the limit yourself.

    • scrollLeft0 / 800 px

The DragScroll component

I wrote this with mouse events in 2022. In that version I kept pos in a let in the component body, so it got reset on every render.

This version uses pointer events, which handle mouse, touch and pen with the same events. It keeps the drag state in useRef. A ref keeps its value across renders, and changing it doesn’t trigger a re-render. That’s exactly what drag state needs.

jsx
import { useRef } from "react";

const DRAG_THRESHOLD = 5; // px

export function DragScroll({ children, style }) {
  const drag = useRef(null);
  const justDragged = useRef(false);

  function handlePointerDown(e) {
    // Touch and pen already scroll natively.
    if (e.pointerType !== "mouse" || e.button !== 0) return;
    justDragged.current = false;
    drag.current = {
      x: e.clientX,
      y: e.clientY,
      left: e.currentTarget.scrollLeft,
      top: e.currentTarget.scrollTop,
      moved: false,
    };
  }

  function handlePointerMove(e) {
    const d = drag.current;
    if (!d || e.buttons !== 1) return;
    const dx = e.clientX - d.x;
    const dy = e.clientY - d.y;

    if (!d.moved) {
      if (Math.hypot(dx, dy) < DRAG_THRESHOLD) return;
      d.moved = true;
      e.currentTarget.setPointerCapture(e.pointerId);
      e.currentTarget.style.userSelect = "none";
    }

    e.currentTarget.scrollLeft = d.left - dx;
    e.currentTarget.scrollTop = d.top - dy;
  }

  function endDrag(e) {
    if (drag.current?.moved) {
      justDragged.current = true;
      e.currentTarget.style.userSelect = "";
    }
    drag.current = null;
  }

  function handleClickCapture(e) {
    // Keyboard clicks have detail 0 and never come from a drag.
    if (!justDragged.current || e.detail === 0) return;
    justDragged.current = false;
    e.preventDefault();
    e.stopPropagation();
  }

  return (
    <div
      style={{ overflow: "auto", ...style }}
      onPointerDown={handlePointerDown}
      onPointerMove={handlePointerMove}
      onPointerUp={endDrag}
      onPointerCancel={endDrag}
      onClickCapture={handleClickCapture}
      onDragStart={(e) => e.preventDefault()}
    >
      {children}
    </div>
  );
}

Two small lines keep the browser from fighting the drag. userSelect = "none" stops text from getting selected while you drag. Cancelling dragstart stops the browser from starting its own drag when you press on an image or a link.

Telling a click from a drag

If there are buttons or links inside, a drag that ends on one of them shouldn’t count as a click on it.

In my first version I handled that with a 250 ms setTimeout and pointer-events: none on the children. Timing is fragile: a slow click looks like a drag and a quick drag looks like a click. Distance is a better measure.

The component uses a threshold of 5 pixels, DRAG_THRESHOLD in the code. Until the mouse has moved that far from where you pressed, nothing scrolls and the press still counts as a click.

Once the mouse passes the threshold, the component takes pointer capture. Capturing a pointer tells the browser to send every event from that mouse to one element until the button is released, even if the mouse leaves the element.

Event order for a click and a dragCompare what happens on either side of the threshold.

Click, under 5 pixels

No capture was taken, so the click reaches the button.

  • pointerdown: position saved
  • pointermove: under the threshold, no scroll
  • pointerup: justDragged is false
  • click: fires on the button (added)

Drag, 5 pixels or more

Capture is still held when the button is released, so the click goes to the container. The button never gets it.

  • pointerdown: position saved
  • pointermove: past the threshold, capture taken, scrolling starts (changed)
  • pointerup: justDragged is true (changed)
  • click: goes to the container, not the button (changed)

I take capture after the threshold, not on pointerdown, on purpose. Pointer Events, the web standard that defines these events, says the click from a captured pointer goes to the element holding the capture. So capturing on pointerdown would mean the buttons inside could never be clicked.

The old version added its listeners to document, because a mouseup outside the element got missed. setPointerCapture fixes that: events keep coming to the element even after the mouse leaves it, and there’s no global listener left to remove.

In a browser that follows the standard, capture alone keeps a drag from clicking a button: the click after the drag goes to the container, and no button inside gets it. handleClickCapture is a safety net for a browser that doesn’t. React’s onClickCapture runs on the container before any element inside sees the click. That’s React’s capture phase: it sets the order of click handlers, while pointer capture decides where the browser sends pointer events. After a drag, justDragged is true, so the container cancels that one click and sets justDragged back to false.

The Firefox 131 build that ships with Playwright 1.48 needed that safety net. With handleClickCapture turned off, the click after a drag went to the button.

For a mouse click, detail is the click count: 1 for the first click, 2 for a double-click. Pressing Enter on a focused button fires a click with detail set to 0, so the check lets it through.

The check matters when a drag ends and no click reaches the container. justDragged then stays true, and without the check the next Enter on a button would get cancelled.

In that Firefox 131 build, releasing a drag outside the container sent the click to the page and left justDragged true.

I ran the component above in a Playwright script, in Chromium 158 and Firefox 159, the browsers that come with Playwright 1.65. Each line is one case, with the result in each browser. The first line uses a copy of the component that takes capture on pointerdown. The fourth line is the same drag with handleClickCapture turned off. “drag out” is a drag released outside the container, followed by Enter on a button.

text
$ node check-drag.mjs
capture on pointerdown, click   chromium 158: button missed         firefox 159: button missed
capture after 5 px, click       chromium 158: button clicked        firefox 159: button clicked
drag, release on a button       chromium 158: button not clicked    firefox 159: button not clicked
same drag, cancel turned off    chromium 158: button not clicked    firefox 159: button not clicked
drag out, then Enter            chromium 158: Enter clicked         firefox 159: Enter clicked

Touch screens and testing

The browser already scrolls on touch, so this code only handles the mouse. If you want to handle touch yourself, set touch-action in CSS. That property tells the browser which touch gestures it may handle on its own. Without it, the browser takes over the scroll and sends pointercancel, which ends your drag.

If you test this behavior, you’ll need a real browser, for example through Playwright. jsdom, the simulated browser most React tests run in, doesn’t calculate layout or scroll positions. I cover the kinds of tests in my React testing article.

References

  1. MDN UIEvent.detail
  2. React useRef documentation
  3. MDN Element.scrollLeft
  4. MDN Element.setPointerCapture
  5. W3C Pointer Events
  6. MDN touch-action
  7. Playwright Mouse API

Written by:

Full Stack Software EngineerSamsun, Türkiye

Full Stack Software Engineer. I started with client sites at an agency in 2019, then worked on embeds, a dashboard and analytics at a startup called Popupsmart.