All hooks / Events and input

useLongPress

364 B minified and brotliedSourceMarkdown✓ Works in all modern browsers

Calls onLongPress when the user presses and holds an element, with mouse, touch, or pen. Returns event handlers to spread onto the element.

Cancels if the pointer is released, leaves, or moves past moveTolerance (so scrolling on a phone doesn't trigger it). Only the primary button counts. After a long press, the click that follows is swallowed, so the element's onClick doesn't also run, and the mobile context menu is suppressed while holding.

Import

import { useLongPress } from '@vincent.ri/react-tils'
// or only this hook
import { useLongPress } from '@vincent.ri/react-tils/useLongPress'

Usage

const longPress = useLongPress(() => setSelected(item.id))
return (
  <li {...longPress} onClick={() => open(item)}>
    {item.name}
  </li>
)

Live demo

Click, or press and hold for half a second.

held 0 · clicked 0

When to use it

Secondary actions on touch devices, e.g. select an item in a list, show a preview, or "hold to delete".

When not to

It is the only way to reach an action; long press is hard to discover and not keyboard accessible, so offer a button or menu too. Add CSS user-select: none; -webkit-touch-callout: none on the element to stop text selection on iOS.

API

function useLongPress(onLongPress: (event: PointerEvent) => void, options?: LongPressOptions): LongPressHandlers
ParameterDescription
onLongPressCalled with the original pointer event once the hold completes.
optionsdelayMs and moveTolerance. Optional.

Returns Handlers to spread onto the element.

Types

export type LongPressOptions = {
  /** How long to hold, in milliseconds. Default `500`. */
  delayMs?: number;
  /** Cancel if the pointer moves more than this many pixels (e.g. the user is scrolling). Default `10`. */
  moveTolerance?: number;
};
/** Spread these onto the element: `<button {...longPress}>`. */
export type LongPressHandlers = {
  onPointerDown: (event: PointerEvent) => void;
  onPointerMove: (event: PointerEvent) => void;
  onPointerUp: () => void;
  onPointerLeave: () => void;
  onPointerCancel: () => void;
  onContextMenu: (event: MouseEvent) => void;
  onClickCapture: (event: MouseEvent) => void;
};

Browser support

UsesChromeEdgeFirefoxSafariChrome AndroidSafari iOS
Pointer eventsWidely available55+12+59+13+55+13+

First version with support, from MDN's compatibility data (web-features 3.42.0, @mdn/browser-compat-data 8.1.5).