use-hold-repeat-handlers

Press-and-hold-to-repeat event handlers for pointer, mouse, touch and keyboard

Usage

use-hold-repeat-handlers returns event handlers that add press-and-hold-to-repeat behavior to an element. It supports all use-hold-repeat options. Press and hold the buttons to change the value:

0

import { useState } from 'react';
import { MinusIcon, PlusIcon } from '@phosphor-icons/react';
import { ActionIcon, Group, Text } from '@mantine/core';
import { useHoldRepeatHandlers } from '@mantine/hooks';

const interval = (step: number) => Math.max(40, 300 - step * 20);

function Demo() {
  const [count, setCount] = useState(0);

  const increment = useHoldRepeatHandlers(() => setCount((c) => c + 1), { delay: 400, interval });
  const decrement = useHoldRepeatHandlers(() => setCount((c) => c - 1), { delay: 400, interval });

  return (
    <Group>
      <ActionIcon {...decrement} variant="default" size="lg" aria-label="Decrement">
        <MinusIcon size={18} />
      </ActionIcon>
      <Text fw={500} w={60} ta="center">{count}</Text>
      <ActionIcon {...increment} variant="default" size="lg" aria-label="Increment">
        <PlusIcon size={18} />
      </ActionIcon>
    </Group>
  );
}

Definition

type UseHoldRepeatEvent = 'pointer' | 'mouse' | 'touch' | 'keyboard';

interface UseHoldRepeatHandlersOptions extends UseHoldRepeatOptions {
  /** Which event handlers to produce. Do not combine `pointer` with `mouse`/`touch`. @default ['pointer'] */
  events?: UseHoldRepeatEvent[];

  /** When `events` includes `keyboard`, only these keys start the hold (e.g. `['ArrowUp']`).
   *  Omit to react to any key. */
  keys?: string[];

  /** Call `event.preventDefault()` on the pointer, mouse and keyboard start event.
   *  Touch start events are exempt (React registers `touchstart` as a passive listener). @default true */
  preventDefault?: boolean;
}

interface UseHoldRepeatHandlersReturnValue {
  onPointerDown?: (event: React.PointerEvent) => void;
  onPointerUp?: (event: React.PointerEvent) => void;
  onPointerLeave?: (event: React.PointerEvent) => void;
  onPointerCancel?: (event: React.PointerEvent) => void;

  onMouseDown?: (event: React.MouseEvent) => void;
  onMouseUp?: (event: React.MouseEvent) => void;
  onMouseLeave?: (event: React.MouseEvent) => void;

  onTouchStart?: (event: React.TouchEvent) => void;
  onTouchEnd?: (event: React.TouchEvent) => void;
  onTouchCancel?: (event: React.TouchEvent) => void;

  onKeyDown?: (event: React.KeyboardEvent) => void;
  onKeyUp?: (event: React.KeyboardEvent) => void;
  onBlur?: (event: React.FocusEvent) => void;

  /** Imperative passthrough from useHoldRepeat for custom wiring */
  start: () => void;
  stop: () => void;
}

function useHoldRepeatHandlers(
  onTrigger: () => void,
  options?: UseHoldRepeatHandlersOptions,
): UseHoldRepeatHandlersReturnValue

Event sources

By default, the hook returns pointer event handlers. Use the events option to choose which events start and stop the hold:

import { useHoldRepeatHandlers } from '@mantine/hooks';

function Demo() {
  const handlers = useHoldRepeatHandlers(() => console.log('tick'), {
    delay: 500,
    interval: 100,
    events: ['mouse', 'touch'],
  });

  return <button {...handlers}>Hold me</button>;
}

Do not combine pointer with mouse or touch, pointer already handles both.

Keyboard

With keyboard events, use the keys option to restrict which keys start the hold:

import { useHoldRepeatHandlers } from '@mantine/hooks';

function Demo() {
  const handlers = useHoldRepeatHandlers(() => console.log('tick'), {
    delay: 500,
    interval: 100,
    events: ['keyboard'],
    keys: ['ArrowUp'],
  });

  return <button {...handlers}>Focus and hold ArrowUp</button>;
}

To handle several keys on one element, call the hook once per key and merge the handlers with mergeEventHandlers. Focus the input and hold ArrowUp or ArrowDown to change the value:

import { useMemo, useState } from 'react';
import { CaretDownIcon, CaretUpIcon } from '@phosphor-icons/react';
import { Stack, TextInput } from '@mantine/core';
import { mergeEventHandlers, useHoldRepeatHandlers } from '@mantine/hooks';

const interval = (step: number) => Math.max(40, 300 - step * 20);

function Demo() {
  const [value, setValue] = useState(0);

  // Drive the same input from two keys by filtering each instance with the `keys` option
  const increment = useHoldRepeatHandlers(() => setValue((v) => v + 1), {
    events: ['keyboard'],
    keys: ['ArrowUp'],
    delay: 400,
    interval,
  });

  const decrement = useHoldRepeatHandlers(() => setValue((v) => v - 1), {
    events: ['keyboard'],
    keys: ['ArrowDown'],
    delay: 400,
    interval,
  });

  // Combine both handler bundles into one set of onKeyDown/onKeyUp props
  const handlers = useMemo(() => mergeEventHandlers(increment, decrement), [increment, decrement]);

  return (
    <TextInput
      {...handlers}
      label="Focus and hold ArrowUp / ArrowDown"
      value={value.toString()}
      readOnly
      w={260}
      rightSection={
        <Stack gap={0} align="center">
          <CaretUpIcon size={12} />
          <CaretDownIcon size={12} />
        </Stack>
      }
    />
  );
}

Combining handler bundles

mergeEventHandlers merges several objects with event handlers into one. Handlers with the same name are called in order:

import { mergeEventHandlers, useHoldRepeatHandlers } from '@mantine/hooks';

function Demo() {
  const up = useHoldRepeatHandlers(increment, { events: ['keyboard'], keys: ['ArrowUp'] });
  const down = useHoldRepeatHandlers(decrement, { events: ['keyboard'], keys: ['ArrowDown'] });

  return <input {...mergeEventHandlers(up, down)} />;
}

Wrap the call in useMemo if you need stable handler references.

preventDefault

By default, event.preventDefault() is called on the start event. Set preventDefault: false to keep the browser behavior. Touch start events are not prevented, use the touch-action CSS property to stop scrolling during a touch hold:

import { useHoldRepeatHandlers } from '@mantine/hooks';

function Demo() {
  const handlers = useHoldRepeatHandlers(() => console.log('tick'), {
    delay: 500,
    interval: 100,
    preventDefault: false,
  });

  return <button {...handlers}>Hold me</button>;
}

Imperative start/stop

The returned object also includes start and stop functions. Use them to control the hold from events that the handlers do not cover:

import { useHoldRepeatHandlers } from '@mantine/hooks';

function Demo() {
  const handlers = useHoldRepeatHandlers(() => console.log('tick'), {
    delay: 500,
    interval: 100,
  });

  // handlers.start() / handlers.stop() are available for custom control
  return <button {...handlers}>Hold me</button>;
}

Exported types

UseHoldRepeatEvent, UseHoldRepeatHandlersOptions and UseHoldRepeatHandlersReturnValue types are exported from the @mantine/hooks package; you can import them in your application:

import type {
  UseHoldRepeatEvent,
  UseHoldRepeatHandlersOptions,
  UseHoldRepeatHandlersReturnValue,
} from '@mantine/hooks';