Skip to content

useLongPress

useLongPress is a React hook that detects when an element is pressed and held for a specified duration. It handles both mouse and touch events, making it work consistently across desktop and mobile devices.

Interface

ts
function useLongPress<E extends HTMLElement>(
  onLongPress: (event: React.MouseEvent<E> | React.TouchEvent<E>) => void,
  options: UseLongPressOptions
): Object;

Parameters

  • onLongPressrequired · (event: React.MouseEvent<E> | React.TouchEvent<E>) => void

    The callback function to be executed when a long press is detected.

  • optionsUseLongPressOptions

    Configuration options for the long press behavior.

    • options.delaynumber · 500

      The time in milliseconds before triggering the long press. Defaults to 500ms.

    • options.moveThresholdObject

      Maximum movement allowed before canceling a long press.

    • options.moveThreshold.xnumber

      Maximum horizontal movement in pixels.

    • options.moveThreshold.ynumber

      Maximum vertical movement in pixels.

    • options.onClick(event) => void

      Optional function to execute on a normal click (press and release before delay).

    • options.onLongPressEnd(event) => void

      Optional function to execute when a long press ends.

Return Value

  • Object

    handlers to attach to an element.

    • onMouseDown(event: MouseEvent<E> | TouchEvent<E>) => void

      Event handler for mouse down events. - onMouseUp (event
      : MouseEvent | TouchEvent) => void
      - Event handler for mouse up events. - onMouseLeave (event
      : MouseEvent | TouchEvent) => void
      - Event handler for mouse leave events. - onTouchStart (event
      : MouseEvent | TouchEvent) => void
      - Event handler for touch start events. - onTouchEnd (event
      : MouseEvent | TouchEvent) => void
      - Event handler for touch end events. - onMouseMove (event
      : MouseEvent | TouchEvent) => void
      - Event handler for mouse move events. Included if moveThreshold is provided. - onTouchMove (event
      : MouseEvent | TouchEvent) => void
      - Event handler for touch move events. Included if moveThreshold is provided..

Example

tsx
import { useLongPress } from 'react-simplikit';

function ContextMenu() {
  const [menuVisible, setMenuVisible] = useState(false);

  const longPressHandlers = useLongPress(
    () => setMenuVisible(true),
    {
      delay: 400,
      onClick: () => console.log('Normal click'),
      onLongPressEnd: () => console.log('Long press completed')
    }
  );

  return (
    <div>
      <button {...longPressHandlers}>Press and hold</button>
      {menuVisible && <div className="context-menu">Context Menu</div>}
    </div>
  );
}

Released under the MIT License.