0

Component

Hold to confirm

A button you press and hold. Let go early and the fill drains back.

Usage

<HoldButton duration={1200} onConfirm={() => deleteProject()}>
  Hold to delete
</HoldButton>

Source

Copy both files into your project. The component has no dependencies beyond React.

"use client";

import { useEffect, useRef, useState, type KeyboardEvent, type ReactNode } from "react";
import styles from "./hold-button.module.css";

type HoldButtonProps = {
  children: ReactNode;
  /** How long the press must last, in milliseconds. */
  duration?: number;
  /** Shown once the hold completes. */
  doneLabel?: ReactNode;
  onConfirm?: () => void;
};

export function HoldButton({ children, duration = 1200, doneLabel = "Done", onConfirm }: HoldButtonProps) {
  const [progress, setProgress] = useState(0);
  const [done, setDone] = useState(false);
  const holding = useRef(false);
  const value = useRef(0);
  const frame = useRef(0);
  const last = useRef(0);

  useEffect(() => () => cancelAnimationFrame(frame.current), []);

  function tick(now: number) {
    const step = (now - last.current) / duration;
    last.current = now;
    // Filling takes the full duration; letting go drains it back faster.
    value.current = Math.min(1, Math.max(0, value.current + (holding.current ? step : -step * 2.5)));
    setProgress(value.current);

    if (value.current >= 1) {
      holding.current = false;
      setDone(true);
      onConfirm?.();
      return;
    }
    if (value.current <= 0 && !holding.current) return;
    frame.current = requestAnimationFrame(tick);
  }

  function start() {
    if (done || holding.current) return;
    holding.current = true;
    cancelAnimationFrame(frame.current);
    last.current = performance.now();
    frame.current = requestAnimationFrame(tick);
  }

  function stop() {
    holding.current = false;
  }

  function onKeyDown(event: KeyboardEvent<HTMLButtonElement>) {
    if ((event.key === " " || event.key === "Enter") && !event.repeat) {
      event.preventDefault();
      start();
    }
  }

  function onKeyUp(event: KeyboardEvent<HTMLButtonElement>) {
    if (event.key === " " || event.key === "Enter") stop();
  }

  return (
    <button
      type="button"
      className={styles.hold}
      data-done={done ? "true" : "false"}
      onPointerDown={start}
      onPointerUp={stop}
      onPointerLeave={stop}
      onPointerCancel={stop}
      onKeyDown={onKeyDown}
      onKeyUp={onKeyUp}
      onContextMenu={(event) => event.preventDefault()}
    >
      <span className={styles.fill} style={{ transform: `scaleX(${progress})` }} aria-hidden="true" />
      <span className={styles.label}>{done ? doneLabel : children}</span>
      <span className={styles.hint} aria-live="polite">
        {done ? "Confirmed" : ""}
      </span>
    </button>
  );
}