Skip to content
Browse documentation

A deliberate action, held for a moment: the ring fills, the label changes, and confirmation settles into a check.

Used forDestructive actionsPayments and transfersPublishing and deploysBulk actions

Install with the shadcn CLI

$ npx shadcn@latest add @hairline/hold-to-confirm

Older shadcn CLI, or a network that blocks ui.shadcn.com? Install by URL: shadcn add https://hairlineui.com/r/hold-to-confirm.json. More

Used in a block

All blocks

Templates

Need the whole page?

65 Next.js landing pages, each designed from scratch. Try any of them live; one is $39, all of them $159, and 8 are free.

Where it’s used

  • Destructive actions

    Delete a project, a workspace or an account.

  • Payments and transfers

    Send a payment or a payout that can’t easily be called back.

  • Publishing and deploys

    Publish to production or send a campaign to everyone.

  • Bulk actions

    Archive hundreds of records in one go.

What it handles for you

A confirm dialog interrupts the page, and people click through it without reading. Holding a button asks for intention without opening anything.

Instead of wiring upa confirm dialoghold timer codea progress ringpending and error statescancel-on-release logic
  1. Intent without a dialog

    Press and hold while a fine ring fills round the icon. The hold takes 1.1 seconds by default, between 0.3 and 5.

  2. Letting go cancels

    Releasing early, pressing Escape, leaving the button or losing focus resets the ring.

  3. It runs once

    The callback runs once after the hold, and a normal click never triggers it.

  4. It shows the result

    The label morphs, a spinner shows while the promise runs, then a drawn check or an alert.

  5. Retry with another hold

    If the callback fails, the button shows the error and the next hold tries again.

  6. Works from the keyboard

    Hold Space or Enter. Key repeat doesn’t restart the timer, and announcements live outside the button.

Overview

Give an important action a little intention without opening another dialog. Press and hold while a fine progress ring traces around the icon. Release early and it returns to rest. Cross the threshold and the same button moves through pending, success or error, with a morphing label and drawn check. The action runs once, and an error can be retried with another hold.

States

hold
The icon ring fills linearly over the configured threshold (1100ms by default). A short press does not confirm.
release
Early release, Escape, focus loss or pointer interruption cancels the hold. The ring resets over 240ms.
pending
After the threshold, the callback runs once. The label morphs and the progress icon gives way to a spinner.
success / error
A resolved callback draws a check; a rejected callback shows an alert and offers another hold. The button resets after 2200ms by default.

Usage

usage.tsx
import { HoldToConfirm } from "@/components/hold-to-confirm";<HoldToConfirm  labels={{ idle: "Hold to archive", pending: "Archiving", success: "Archived" }}  onConfirm={async () => { await archiveProject(); }}/>

Depends on lucide-react, installed for you by the CLI along with the keyframes it needs.

Works with

Connect a deliberate action

The callback owns the actual operation. Reject its promise to show an error; the component never invents a successful result.

example.tsx
"use client";import { HoldToConfirm } from "@/components/hold-to-confirm";export function ArchiveProject({ id }: { id: string }) {  return <HoldToConfirm labels={{ idle: "Hold to archive", success: "Archived" }}    onConfirm={async () => {      const response = await fetch("/api/projects/" + id + "/archive", { method: "POST" });      if (!response.ok) throw new Error("Archive failed");    }} />;}

Props

onConfirm
() => void | Promise<void>
Runs once after the hold threshold. Resolves to success or rejects to error.
duration= 1100
number
Required hold in milliseconds, clamped to 300–5000.
resetAfter= 2200
number
Delay before returning to idle. Set 0 to keep the result visible.
labels
Partial<Record<HoldStatus, string>>
Labels for idle, holding, pending, success and error.
onStatusChange
(status: HoldStatus) => void
Every change of state, e.g. to move something else in step with the hold.
icon
ReactNode
Idle and holding icon. Defaults to a fingerprint.
disabled= false
boolean
Disables the action and cancels an active hold.

Accessibility and motion

  • Hold the pointer, Space or Enter to confirm. Key repeat does not restart the timer, and a normal click never triggers the callback.
  • Releasing early, leaving the button, losing focus, Escape or a hidden browser tab cancels an incomplete hold. A completed action continues through its promise.
  • State announcements live outside the button. The button retains focus while pending or showing its result.
  • Reduced motion removes icon movement and spinning. The functional progress ring still communicates the hold duration.
  • Use clear action labels and provide undo in your application where appropriate.

Requirements

React 19, Tailwind CSS v4 and shadcn/ui theme variables (any style, light and dark). Icons from lucide-react.

The CLI also installs Text morph.

Source

'use client';import * as React from 'react';import { CircleAlert, Fingerprint } from 'lucide-react';import { TextMorph } from './text-morph';import { INTERACTION_FOCUS, interactionIcon, useInteractionReducedMotion } from './ui-interaction-motion';import { useHoldConfirm, type HoldStatus } from './use-hold-confirm';export type { HoldStatus } from './use-hold-confirm';export interface HoldToConfirmProps extends Omit<React.ButtonHTMLAttributes<HTMLButtonElement>, 'onClick' | 'children'> {  onConfirm: () => void | Promise<void>;  duration?: number;  resetAfter?: number;  labels?: Partial<Record<HoldStatus, string>>;  icon?: React.ReactNode;  /** Every change of state: holding, pending, success, error, back to idle. */  onStatusChange?: (status: HoldStatus) => void;}const LABELS = { idle: 'Hold to confirm', holding: 'Keep holding', pending: 'Confirming', success: 'Confirmed', error: 'Hold to retry' };/** Press and keep holding. The threshold owns the action; a click never submits it. */export function HoldToConfirm({ onConfirm, duration = 1100, resetAfter = 2200, labels, icon, onStatusChange, disabled = false, className = '', ...props }: HoldToConfirmProps) {  const reduced = useInteractionReducedMotion();  const delay = Number.isFinite(duration) ? Math.max(300, Math.min(5000, duration)) : 1100;  const { status, progress, begin, cancel } = useHoldConfirm(onConfirm, delay, resetAfter, disabled, reduced);  const report = React.useRef(onStatusChange);  React.useLayoutEffect(() => {    report.current = onStatusChange;  });  React.useEffect(() => {    report.current?.(status);  }, [status]);  const text = { ...LABELS, ...labels }[status];  const hint = React.useId();  const pending = status === 'pending', succeeded = status === 'success';  return <>    <button {...props} type="button" disabled={disabled} aria-describedby={hint} aria-busy={pending || undefined} aria-disabled={pending || succeeded || disabled || undefined}      onPointerDown={(event) => {        if (event.button !== 0 || !event.isPrimary) return;        event.currentTarget.setPointerCapture(event.pointerId); event.currentTarget.focus({ preventScroll: true }); begin(`pointer:${event.pointerId}`);      }}      onPointerMove={(event) => {        if (!event.currentTarget.hasPointerCapture(event.pointerId)) return;        const rect = event.currentTarget.getBoundingClientRect();        if (event.clientX < rect.left || event.clientX > rect.right || event.clientY < rect.top || event.clientY > rect.bottom) cancel(`pointer:${event.pointerId}`);      }}      onPointerUp={(event) => cancel(`pointer:${event.pointerId}`)} onPointerCancel={(event) => cancel(`pointer:${event.pointerId}`)} onLostPointerCapture={(event) => cancel(`pointer:${event.pointerId}`)} onPointerLeave={(event) => cancel(`pointer:${event.pointerId}`)} onBlur={() => cancel()}      onKeyDown={(event) => {        if (event.key === 'Escape') { event.preventDefault(); cancel(); }        if (event.key === ' ' || event.key === 'Enter') { event.preventDefault(); if (!event.repeat) begin(`key:${event.key}`); }      }} onKeyUp={(event) => { if (event.key === ' ' || event.key === 'Enter') { event.preventDefault(); cancel(`key:${event.key}`); } }}      onClick={(event) => event.preventDefault()}      className={`cursor-pointer disabled:cursor-default aria-disabled:cursor-default relative inline-flex h-11 select-none items-center justify-center gap-2.5 overflow-clip rounded-full border px-4 text-[13px] font-medium transition-colors disabled:opacity-40 ${status === 'error' ? 'border-destructive/40 bg-destructive/5 text-destructive' : 'border-primary bg-primary text-primary-foreground hover:bg-primary/90'} ${INTERACTION_FOCUS} ${className}`}      style={{ touchAction: 'none', ...props.style }}>      <span aria-hidden="true" className="relative size-5 shrink-0">        <span className="absolute inset-0 flex items-center justify-center [&>svg]:size-4" style={interactionIcon(status === 'idle' || status === 'holding', reduced)}>{icon ?? <Fingerprint />}</span>        <svg viewBox="0 0 24 24" className="absolute -inset-1 size-7 -rotate-90" style={{ opacity: status === 'holding' ? 1 : 0, transition: reduced ? 'none' : 'opacity 180ms ease-out' }}>          <circle cx="12" cy="12" r="10.5" fill="none" stroke="currentColor" strokeOpacity="0.2" strokeWidth="1" />          <circle ref={progress} cx="12" cy="12" r="10.5" pathLength="1" fill="none" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" strokeDasharray="1" strokeDashoffset="1" />        </svg>        <span className="absolute inset-0 flex items-center justify-center" style={interactionIcon(pending, reduced)}><span className={`size-4 rounded-full border-[1.5px] border-current/30 border-t-current ${pending && !reduced ? 'animate-spin' : ''}`} /></span>        <svg viewBox="0 0 20 20" className="absolute inset-0 size-5" style={interactionIcon(succeeded, reduced)}><path d="m4 10 4 4 8-8" fill="none" stroke="currentColor" strokeWidth="1.6" strokeLinecap="round" strokeLinejoin="round" pathLength="1" style={{ strokeDasharray: 1, strokeDashoffset: succeeded ? 0 : 1, transition: reduced ? 'none' : 'stroke-dashoffset 380ms ease-out 80ms' }} /></svg>        <CircleAlert className="absolute inset-0 size-5" style={interactionIcon(status === 'error', reduced)} />      </span>      <TextMorph>{text}</TextMorph>    </button>    <span id={hint} className="sr-only">Hold the pointer, Space or Enter for {delay / 1000} seconds. Release early or press Escape to cancel.</span>    <span role="status" className="sr-only">{status === 'idle' ? '' : text}</span>  </>;}

Registry item: /r/hold-to-confirm.json