Home/Components/Buttons/Hold to Confirm Button - React Press and Hold Animation
Code · Live Preview
Componenttsx
"use client";

// src/components/HoldButton/HoldButton.tsx
import {
  AnimatePresence,
  animate,
  motion,
  useAnimationControls,
  useMotionValue,
  useReducedMotion,
  useTransform,
  type AnimationPlaybackControls,
} from "motion/react";
import { useEffect, useId, useRef, useState, type ReactNode } from "react";

type Status = "idle" | "holding" | "done";

type HoldButtonProps = {
  /** Text before holding */
  label?: string;
  /** Text while holding */
  holdingLabel?: string;
  /** Text after it's confirmed */
  doneLabel?: string;
  /** Tip shown when someone clicks instead of holding */
  hint?: string;
  /** How long to hold, in ms */
  duration?: number;
  /** Main color - red for delete, or your brand color */
  color?: string;
  /** Icon before the label (default: trash can) */
  icon?: ReactNode;
  /** Runs once the hold is complete */
  onConfirm?: () => void;
  /** Go back to the start after this many ms. false = stay done */
  resetAfter?: number | false;
  disabled?: boolean;
  className?: string;
};

// Quick press shorter than this counts as a click, so we show the hint
const CLICK_MS = 250;

// Burst dots: angle in degrees
const BURST = [0, 45, 90, 135, 180, 225, 270, 315];

function TrashIcon() {
  return (
    <svg viewBox="0 0 24 24" className="size-4 shrink-0" fill="none" stroke="currentColor" strokeWidth={2} strokeLinecap="round" strokeLinejoin="round" aria-hidden="true">
      <path d="M3 6h18M8 6V4h8v2M6 6l1 14h10l1-14M10 11v5M14 11v5" />
    </svg>
  );
}

function CheckIcon({ draw }: { draw: boolean }) {
  return (
    <svg viewBox="0 0 24 24" className="size-4 shrink-0" fill="none" stroke="currentColor" strokeWidth={2.6} strokeLinecap="round" strokeLinejoin="round" aria-hidden="true">
      <motion.path
        d="M5 12.5l4.5 4.5L19 7.5"
        initial={{ pathLength: draw ? 0 : 1 }}
        animate={{ pathLength: 1 }}
        transition={{ duration: 0.35, ease: "easeOut", delay: 0.05 }}
      />
    </svg>
  );
}

export function HoldButton({
  label = "Hold to delete",
  holdingLabel = "Keep holding",
  doneLabel = "Deleted",
  hint = "Press and hold to confirm",
  duration = 1500,
  color = "#DC2626",
  icon = <TrashIcon />,
  onConfirm,
  resetAfter = 2200,
  disabled = false,
  className = "",
}: HoldButtonProps) {
  const reduce = useReducedMotion();
  const hintId = useId();
  const controls = useAnimationControls();

  const [status, setStatus] = useState<Status>("idle");
  const [showHint, setShowHint] = useState(false);
  const [bursts, setBursts] = useState(0);

  // Refs, so timers and animation callbacks always see the latest values
  const statusRef = useRef<Status>("idle");
  const pressedAt = useRef(0);
  const anim = useRef<AnimationPlaybackControls | null>(null);
  const timers = useRef<number[]>([]);

  // 0 = empty, 1 = full
  const progress = useMotionValue(0);
  // The colored layer is revealed from left to right
  const clip = useTransform(progress, (p) => `inset(0 ${(1 - p) * 100}% 0 0)`);

  const setBoth = (s: Status) => {
    statusRef.current = s;
    setStatus(s);
  };

  const later = (fn: () => void, ms: number) => {
    timers.current.push(window.setTimeout(fn, ms));
  };

  useEffect(
    () => () => {
      anim.current?.stop();
      timers.current.forEach(clearTimeout);
    },
    [],
  );

  const complete = () => {
    setBoth("done");
    setBursts((n) => n + 1);
    navigator.vibrate?.(30);
    onConfirm?.();
    if (resetAfter !== false) {
      later(() => {
        setBoth("idle");
        anim.current = animate(progress, 0, { duration: reduce ? 0 : 0.4, ease: "easeOut" });
      }, resetAfter);
    }
  };

  const start = () => {
    if (disabled || statusRef.current !== "idle") return;
    pressedAt.current = Date.now();
    setShowHint(false);
    setBoth("holding");
    anim.current?.stop();
    // Continue from wherever the fill is now
    const remaining = ((1 - progress.get()) * duration) / 1000;
    anim.current = animate(progress, 1, {
      duration: remaining,
      ease: "linear",
      onComplete: complete,
    });
  };

  const release = () => {
    if (statusRef.current !== "holding") return;
    anim.current?.stop();
    setBoth("idle");
    // Drain back to empty
    anim.current = animate(progress, 0, reduce ? { duration: 0 } : { type: "spring", stiffness: 260, damping: 28 });

    // A quick click instead of a hold: shake and show the tip
    if (Date.now() - pressedAt.current < CLICK_MS) {
      setShowHint(true);
      later(() => setShowHint(false), 1800);
      if (!reduce) controls.start({ x: [0, -6, 6, -4, 4, 0], transition: { duration: 0.4 } });
    }
  };

  const text = status === "done" ? doneLabel : status === "holding" ? holdingLabel : label;

  // Same content for the plain layer and the colored layer
  const content = (
    <AnimatePresence mode="popLayout" initial={false}>
      <motion.span
        key={status}
        className="col-start-1 row-start-1 flex items-center justify-center gap-2 whitespace-nowrap"
        initial={reduce ? { opacity: 0 } : { y: 14, opacity: 0 }}
        animate={{ y: 0, opacity: 1 }}
        exit={reduce ? { opacity: 0 } : { y: -14, opacity: 0 }}
        transition={{ duration: 0.2, ease: "easeOut" }}
      >
        {status === "done" ? <CheckIcon draw={!reduce} /> : icon}
        {text}
      </motion.span>
    </AnimatePresence>
  );

  // Invisible copies of every label, so the button is always as wide
  // as its longest label and never jumps in size
  const sizers = [label, holdingLabel, doneLabel].map((t) => (
    <span key={t} className="invisible col-start-1 row-start-1 flex items-center gap-2 whitespace-nowrap" aria-hidden="true">
      <span className="size-4" />
      {t}
    </span>
  ));

  return (
    <div className={`relative inline-flex flex-col items-center ${className}`}>
      <motion.button
        type="button"
        animate={controls}
        whileTap={disabled || reduce ? undefined : { scale: 0.97 }}
        onPointerDown={(e) => {
          if (e.button !== 0) return;
          e.currentTarget.setPointerCapture(e.pointerId);
          start();
        }}
        onPointerUp={release}
        onPointerCancel={release}
        onLostPointerCapture={release}
        onKeyDown={(e) => {
          if (e.key === " " || e.key === "Enter") {
            e.preventDefault();
            if (!e.repeat) start();
          }
        }}
        onKeyUp={(e) => {
          if (e.key === " " || e.key === "Enter") release();
        }}
        onBlur={release}
        onContextMenu={(e) => e.preventDefault()}
        aria-describedby={hintId}
        aria-disabled={disabled}
        className="relative h-11 touch-none overflow-hidden rounded-full px-5 text-sm font-semibold select-none focus-visible:outline-2 focus-visible:outline-offset-2 disabled:cursor-not-allowed aria-disabled:cursor-not-allowed aria-disabled:opacity-50"
        style={{
          color,
          outlineColor: color,
          background: `color-mix(in srgb, ${color} 12%, transparent)`,
          WebkitTouchCallout: "none",
        }}
      >
        {/* Plain layer */}
        <span className="grid">
          {sizers}
          {content}
        </span>

        {/* Colored layer, revealed as you hold */}
        <motion.span
          className="absolute inset-0 grid place-items-center px-5 text-white"
          style={{ background: color, clipPath: clip }}
          aria-hidden="true"
        >
          <span className="grid">{content}</span>
        </motion.span>
      </motion.button>

      {/* Burst when confirmed */}
      {!reduce && (
        <AnimatePresence>
          {status === "done" && (
            <span key={bursts} className="pointer-events-none absolute top-[22px] left-1/2" aria-hidden="true">
              {BURST.map((deg) => {
                const a = (deg * Math.PI) / 180;
                return (
                  <motion.span
                    key={deg}
                    className="absolute size-1.5 -translate-1/2 rounded-full"
                    style={{ background: color }}
                    initial={{ x: 0, y: 0, opacity: 1, scale: 1 }}
                    animate={{ x: Math.cos(a) * 70, y: Math.sin(a) * 34, opacity: 0, scale: 0.4 }}
                    exit={{ opacity: 0 }}
                    transition={{ duration: 0.6, ease: "easeOut" }}
                  />
                );
              })}
            </span>
          )}
        </AnimatePresence>
      )}

      {/* Tip for people who click instead of hold */}
      <span id={hintId} className="sr-only">
        {hint}
      </span>
      <AnimatePresence>
        {showHint && (
          <motion.span
            className="absolute top-full mt-2 text-xs font-medium whitespace-nowrap text-neutral-500 dark:text-neutral-400"
            initial={{ opacity: 0, y: -4 }}
            animate={{ opacity: 1, y: 0 }}
            exit={{ opacity: 0, y: -4 }}
            aria-hidden="true"
          >
            {hint}
          </motion.span>
        )}
      </AnimatePresence>

      {/* Tells screen readers when it's done */}
      <span className="sr-only" role="status" aria-live="polite">
        {status === "done" ? doneLabel : ""}
      </span>
    </div>
  );
}

export default HoldButton;
// Component Source: https://codekk.dev
DesktopSandpackTailwind v4

Component details

Overview, install command, dependencies, and project links.

A hold to confirm button for React built with TypeScript, Motion, and Tailwind CSS v4. It protects risky actions like deleting an account, sending a payment, or publishing a post, because a quick accidental click is not enough. You have to press and hold. While you hold, a solid color fill sweeps across the button from left to right. The text changes color exactly at the edge of the fill, so the part that is filled shows white text and the rest shows colored text, which makes the progress feel precise. The label slides to "Keep holding" while you press. If you let go early, the fill springs back to empty, and if you press again it continues from where the fill is right now instead of starting over. When the hold is complete, the label slides to a check mark that draws itself and the done text, a small burst of dots pops around the button, and phones give a short vibration. If someone just clicks instead of holding, the button gives a little shake and shows a "Press and hold to confirm" tip under it. The button is always as wide as its longest label, so it never jumps in size when the text changes. The color, labels, icon, and hold time can all be changed, and resetAfter decides if the button goes back to the start or stays confirmed. It works with mouse, touch, and keyboard: hold Space or Enter. Long press menus on phones are blocked so they don't get in the way. Screen readers hear the hold instruction, and a polite live region announces the done text. When prefers-reduced-motion is enabled, the shake, burst, and sliding text are turned off, but the fill still shows progress. "use client" is included, so it works in Vite, Create React App, and Next.js.

Install

terminal
npm
npm create vite@latest my-app -- --template react-ts cd my-app npm install motion

Dependencies

motion
Added Nov 25, 2026

Discussion

Feedback, implementation tips, and usage notes.

0 threads

Comments

Sign in to join the conversation