Skip to content
Browse documentation

The button at the end of a checkout, through the whole wait: the card being charged, a line of light while it pays, and a receipt that slides out from under it.

Used forCheckoutUpgrade and billingTickets and bookingsTop-ups and tips

Install with the shadcn CLI

$ npx shadcn@latest add https://hairlineui.com/r/pay-button.json

Registered the namespace? Then it’s shadcn add @hairline/pay-button. Set it up

Templates

Need the whole page?

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

All 61 templates

Where it’s used

  • Checkout

    The last button of a store's checkout, under the order summary.

  • Upgrade and billing

    Pay for a plan change or an overdue invoice inside the app.

  • Tickets and bookings

    Pay for seats or a stay, with the booking reference on the receipt.

  • Top-ups and tips

    Add credit to a wallet or tip a creator in one press.

What it handles for you

The seconds after Pay are the most anxious in a checkout. The usual button spins with no word on which card is being charged, then hands the answer to a different screen, so people tap again or refresh.

Instead of wiring uppayment button loading statepayment success screenpayment declined messagecheckout submit buttonorder confirmation toast
  1. Says what it charges

    While paying, the label names the card or wallet in use, so nobody wonders which one it was.

  2. A wait you can see

    A line of light laps the button for as long as your onPay runs, at least long enough to be seen.

  3. The answer in place

    Paid turns the button green and slides a receipt out from under it, with the reference ready to copy.

  4. Declines say why

    The Error's message slides out of the same slot in red, and the button becomes Try again.

  5. Never pays twice

    It ignores presses while paying and stays paid until it is remounted, so a double tap can't charge again.

  6. Keyboard and screen readers

    A real button; paying, paid with its reference, and the decline reason are announced from a status region.

Overview

Most Pay buttons go grey and spin, and then the page changes or a toast says something. People tap twice, or leave not knowing if they paid. This one stays the place where the answer appears. Press it and the label turns into the card being charged, "Paying with Visa •• 4242", while a line of light laps the button for as long as your onPay runs. When it resolves, the line closes into a whole ring and lets go, the button turns green with a check drawn in it, and a receipt slides out from under it: the reference with a Copy button, the card and the time. If it throws, the button shakes once and says "Try again", and the reason slides out of the same slot; pressing again tucks it back in. The amount rolls when the total changes, so a coupon or a quantity change reads at once.

States

idle
A 48px pill in the primary colour: "Pay $48.00". When the amount changes, its digits roll the way it moved.
paying
The label lifts out and "Paying with Visa •• 4242" rises in with a small card. A bright line with a faint tail laps the button 4px outside it, once every 1.4s, while onPay runs (at least 0.7s).
paid
The line closes into a whole emerald ring that grows a little and fades (1.1s); the button turns green and a check draws itself before "Paid $48.00". The receipt slides out from under the button (0.52s): the reference with Copy, then the card and the time. It stays paid.
copied
The Copy icon turns into a green check for 1.6s.
declined
The button shakes once (±5px, 0.38s) and says "Try again"; the Error's message slides out of the slot in red. Pressing again tucks it back into the button as the line starts again.
reduced motion
No lap, ring, shake or slide: a still outline shows while paying, and the labels and the receipt change in place.

Usage

usage.tsx
import { PayButton } from "@/components/pay-button";<PayButton  amount={48}  method={{ brand: "Visa", last4: "4242" }}  onPay={() => pay(order)}/>

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

Works with

With Stripe

Confirm the PaymentIntent your server created; resolve with its id as the reference, and throw Stripe's message when it is declined. Stripe's own element still takes the card details.

example.tsx
"use client";import { useElements, useStripe } from "@stripe/react-stripe-js";import { PayButton } from "@/components/pay-button";export function PayStep({ total, card }: { total: number; card: { brand: string; last4: string } }) {  const stripe = useStripe();  const elements = useElements();  return (    <PayButton      amount={total}      method={card}      disabled={!stripe || !elements}      onPay={async () => {        const { error, paymentIntent } = await stripe!.confirmPayment({ elements: elements!, redirect: "if_required" });        if (error) throw new Error(error.message ?? "The payment didn't go through.");        return { reference: paymentIntent?.id };      }}    />  );}

Props

amount
number
The total on the button. It rolls when it changes.
method
{ brand: string; last4?: string }
The card or wallet being charged, named while paying and on the receipt.
onPay
() => unknown | Promise<unknown>
Your payment. Resolve when it went through (with { reference } to show it on the receipt); throw an Error to show its message.
format / locales= { style: "currency", currency: "USD" }
Intl.NumberFormatOptions / string | string[]
How the amount is written.
labels
{ pay?, paying?, paid?, retry?, failed? }
The words. pay replaces the whole "Pay $48.00"; failed is the reason when the Error has no message.
disabled= false
boolean
Dimmed and unpressable, e.g. until the card details are complete.
sound= false
boolean
Two soft rising notes when it is paid, two falling ones when it is declined (synthesised, no files).
onStatusChange
(status: "idle" | "paying" | "paid" | "error") => void
Every change of state.

Accessibility and motion

  • A real button. While paying and once paid it is aria-disabled, so it keeps focus and ignores presses.
  • Paying (with the card), paid (with the reference) and the decline reason are announced from a status region outside the button.
  • onPay is called once per press, and never while one is in flight. It stays paid until it is remounted (a new key).
  • The line of light is two dashes on one SVG outline, moved by the Web Animations API only while paying; nothing re-renders while it laps.
  • The receipt sits in the layout under the button, so it pushes what follows down instead of covering it. Fills the width it is given (at least 248px).

Requirements

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

The CLI also installs Number roll.

Source

"use client";/* ───────────────────────────────────────────────────────── * PAY BUTTON: the wait between tapping Pay and knowing * *   pay       "Pay $48.00"; the amount rolls when the total *             changes, so a coupon or a quantity reads at once *   paying    the label turns into the card being charged *             ("Paying with Visa •• 4242") and a line of light *             runs round the button while your onPay runs *   paid      the line closes into a ring, the button turns *             green with a check, and a receipt slides out from *             under it: the reference (with Copy), the card and *             the time *   declined  the button shakes once and says "Try again"; the *             reason slides out of the same slot. Pressing again *             tucks it back in and tries again * * One line in your app: <PayButton amount={48} method={{ brand, * last4 }} onPay={() => api.pay(...)} />. Resolve with * { reference } to show it on the receipt; throw an Error to * say why not. It stays paid until it is remounted. * ───────────────────────────────────────────────────────── */import * as React from "react";import { Check, Copy, RotateCcw } from "lucide-react";import { NumberRoll } from "./number-roll";import { EASE_OUT, INTERACTION_FOCUS, INTERACTION_PRESS } from "./ui-interaction-motion";import { playSound } from "./ui-sounds";export interface PayMethod {  /** "Visa", "Mastercard", "Amex", "Apple Pay"… */  brand: string;  /** The card's last four digits, if it has them. */  last4?: string;}export type PayButtonStatus = "idle" | "paying" | "paid" | "error";export interface PayButtonProps {  /** The total, written on the button with `format`. It rolls when it changes. */  amount: number;  /** The card or wallet being charged, shown while paying and on the receipt. */  method?: PayMethod;  /** Your payment. Resolve (with `{ reference }` to show it) when it went through; throw an Error to say why not. */  onPay: () => unknown | Promise<unknown>;  format?: Intl.NumberFormatOptions;  locales?: string | string[];  /** The words. `pay` replaces the whole "Pay $48.00". */  labels?: Partial<Record<"pay" | "paying" | "paid" | "retry" | "failed", string>>;  disabled?: boolean;  /** Soft synthesised sounds when it goes through or fails. */  sound?: boolean;  onStatusChange?: (status: PayButtonStatus) => void;  className?: string;}const USD: Intl.NumberFormatOptions = { style: "currency", currency: "USD" };const MIN_PENDING = 700; // the line goes round at least this long, so "paying" is seenconst LAP = 1400; // one lap of the line, msconst TUCK = 14; // how far the receipt's top sits behind the buttonconst reducedQuery = "(prefers-reduced-motion: reduce)";const subscribeReduced = (onChange: () => void) => {  const query = window.matchMedia(reducedQuery);  query.addEventListener("change", onChange);  return () => query.removeEventListener("change", onChange);};const useReducedMotion = () => React.useSyncExternalStore(subscribeReduced, () => window.matchMedia(reducedQuery).matches, () => false);const subscribeNothing = () => () => {};const useHydrated = () => React.useSyncExternalStore(subscribeNothing, () => true, () => false);type Phase = "idle" | "paying" | "paid" | "failed";type Note = { kind: "receipt"; reference?: string; at: Date } | { kind: "error"; message: string };// The order lines come in: a later one rises from below, an earlier one comes back down from above.const LINES = ["pay", "retry", "paying", "paid"] as const;type Line = (typeof LINES)[number];const referenceOf = (result: unknown) => {  if (result && typeof result === "object" && "reference" in result) {    const ref = (result as { reference?: unknown }).reference;    if (typeof ref === "string" || typeof ref === "number") return String(ref);  }  return undefined;};/** A small card, drawn in the button's own colour. */function CardGlyph() {  return (    <svg aria-hidden="true" viewBox="0 0 22 16" className="size-[22px] h-4 shrink-0">      <rect x="0.75" y="0.75" width="20.5" height="14.5" rx="3" fill="none" stroke="currentColor" strokeWidth="1.5" />      <path d="M1 5.25h20" stroke="currentColor" strokeWidth="1.5" />      <rect x="3.5" y="9.5" width="5" height="2.5" rx="1" fill="currentColor" />    </svg>  );}export function PayButton({  amount,  method,  onPay,  format = USD,  locales,  labels,  disabled = false,  sound = false,  onStatusChange,  className = "",}: PayButtonProps) {  const reduced = useReducedMotion();  const hydrated = useHydrated();  const locale = locales ?? (hydrated ? undefined : "en-US");  const money = new Intl.NumberFormat(locale, format).format(amount);  const card = method ? `${method.brand}${method.last4 ? ` •• ${method.last4}` : ""}` : "";  const cardSpoken = method ? `${method.brand}${method.last4 ? ` ending ${method.last4}` : ""}` : "";  const words = {    paying: method ? "Paying with" : "Paying…",    paid: "Paid",    retry: "Try again",    failed: "The payment didn't go through.",    ...labels,  };  const [phase, setPhase] = React.useState<Phase>("idle");  const [note, setNote] = React.useState<Note | null>(null);  const [copied, setCopied] = React.useState(false);  const buttonRef = React.useRef<HTMLButtonElement>(null);  const headRef = React.useRef<SVGRectElement>(null);  const tailRef = React.useRef<SVGRectElement>(null);  const ringRef = React.useRef<SVGRectElement>(null);  const timers = React.useRef(new Set<ReturnType<typeof setTimeout>>());  const busy = React.useRef(false);  const latest = React.useRef({ onPay, sound, onStatusChange, failed: words.failed });  React.useLayoutEffect(() => {    latest.current = { onPay, sound, onStatusChange, failed: words.failed };  });  React.useEffect(() => {    const pending = timers.current;    return () => {      for (const id of pending) clearTimeout(id);      pending.clear();    };  }, []);  const later = (fn: () => void, ms: number) => {    const id = setTimeout(() => {      timers.current.delete(id);      fn();    }, ms);    timers.current.add(id);  };  const pay = async (event: React.MouseEvent<HTMLButtonElement>) => {    if (busy.current || phase === "paid" || disabled) return;    busy.current = true;    const started = event.timeStamp;    setPhase("paying");    let outcome: Note;    try {      const result = await latest.current.onPay();      outcome = { kind: "receipt", reference: referenceOf(result), at: new Date() };    } catch (error) {      outcome = { kind: "error", message: error instanceof Error && error.message ? error.message : latest.current.failed };    }    later(() => {      busy.current = false;      setNote(outcome);      setPhase(outcome.kind === "receipt" ? "paid" : "failed");      if (latest.current.sound) playSound(outcome.kind === "receipt" ? "success" : "error", 0.4);    }, Math.max(0, started + MIN_PENDING - performance.now()));  };  // The line of light: a bright head and a faint tail, lapping the button while it pays.  React.useEffect(() => {    if (phase !== "paying" || reduced) return;    const timing: KeyframeAnimationOptions = { duration: LAP, iterations: Infinity, easing: "linear" };    const head = headRef.current?.animate([{ strokeDashoffset: 0 }, { strokeDashoffset: -100 }], timing);    const tail = tailRef.current?.animate([{ strokeDashoffset: 20 }, { strokeDashoffset: -80 }], timing);    return () => {      head?.cancel();      tail?.cancel();    };  }, [phase, reduced]);  // Paid: the line closes into a whole ring, which lets go of the button. Declined: one shake.  React.useEffect(() => {    if (reduced) return;    if (phase === "paid") {      const ring = ringRef.current?.animate(        [          { strokeDashoffset: 1, opacity: 1, transform: "scale(1)" },          { strokeDashoffset: 0, opacity: 1, transform: "scale(1)", offset: 0.45 },          { strokeDashoffset: 0, opacity: 0, transform: "scale(1.04)" },        ],        { duration: 1100, easing: EASE_OUT, fill: "backwards" },      );      return () => ring?.cancel();    }    if (phase === "failed") {      const shake = buttonRef.current?.animate(        [          { transform: "translateX(0)" },          { transform: "translateX(-5px)" },          { transform: "translateX(4px)" },          { transform: "translateX(-2px)" },          { transform: "translateX(0)" },        ],        { duration: 380, easing: "ease-out" },      );      return () => shake?.cancel();    }  }, [phase, reduced]);  const status: PayButtonStatus = phase === "failed" ? "error" : phase;  React.useEffect(() => {    latest.current.onStatusChange?.(status);  }, [status]);  const copy = () => {    if (note?.kind !== "receipt" || !note.reference) return;    try {      void navigator.clipboard?.writeText(note.reference).catch(() => {});    } catch {}    setCopied(true);    later(() => setCopied(false), 1600);  };  const line: Line = phase === "paid" ? "paid" : phase === "paying" ? "paying" : phase === "failed" ? "retry" : "pay";  const fade = (ms: number, delay = 0) => (reduced ? "none" : `opacity ${ms}ms ${EASE_OUT} ${delay}ms, transform ${ms + 120}ms ${EASE_OUT} ${delay}ms, filter ${ms}ms ${EASE_OUT} ${delay}ms`);  const lineStyle = (name: Line): React.CSSProperties => {    const on = name === line;    const offset = LINES.indexOf(name) < LINES.indexOf(line) ? -8 : 8;    return {      opacity: on ? 1 : 0,      transform: on ? "none" : `translate3d(0,${offset}px,0)`,      filter: on ? "blur(0px)" : "blur(4px)",      transition: on ? fade(300, 90) : fade(160),    };  };  const paid = phase === "paid";  const open = phase === "paid" || phase === "failed";  const slide = reduced ? "none" : open ? `520ms ${EASE_OUT} 160ms` : `300ms ${EASE_OUT}`;  const time =    note?.kind === "receipt" ? new Intl.DateTimeFormat(locale, { hour: "numeric", minute: "2-digit" }).format(note.at) : "";  const announce =    phase === "paying"      ? `Paying ${money}${cardSpoken ? ` with ${cardSpoken}` : ""}`      : phase === "paid"        ? `Paid ${money}.${note?.kind === "receipt" && note.reference ? ` Reference ${note.reference}.` : ""}`        : phase === "failed" && note?.kind === "error"          ? note.message          : "";  const label = (name: Line) => `absolute inset-0 flex items-center justify-center gap-2 px-5 ${name === line ? "" : "pointer-events-none"}`;  return (    <div role="group" aria-label={`Pay ${money}`} className={`w-full min-w-[248px] ${className}`}>      <div className="relative">        {/* The line of light, 4px outside the button, and the ring it closes into. */}        <svg          aria-hidden="true"          className="pointer-events-none absolute -left-1 -top-1 h-[calc(100%+8px)] w-[calc(100%+8px)] overflow-visible"          style={{ opacity: phase === "paying" ? 1 : 0, transition: reduced ? "none" : `opacity 220ms ${EASE_OUT}` }}        >          <rect            ref={tailRef}            width="100%"            height="100%"            rx="28"            fill="none"            stroke="var(--primary)"            strokeOpacity={reduced ? 0.35 : 0.28}            strokeWidth="2"            pathLength={100}            strokeDasharray={reduced ? "100 0" : "28 72"}            strokeDashoffset={20}          />          {!reduced ? (            <rect ref={headRef} width="100%" height="100%" rx="28" fill="none" stroke="var(--primary)" strokeWidth="2" strokeLinecap="round" pathLength={100} strokeDasharray="8 92" />          ) : null}        </svg>        <svg aria-hidden="true" className="pointer-events-none absolute -left-1 -top-1 h-[calc(100%+8px)] w-[calc(100%+8px)] overflow-visible">          <rect            ref={ringRef}            width="100%"            height="100%"            rx="28"            fill="none"            className="stroke-emerald-500"            strokeWidth="2"            pathLength={1}            strokeDasharray="1 1"            style={{ opacity: 0, transformOrigin: "center", transformBox: "fill-box" }}          />        </svg>        <button          ref={buttonRef}          type="button"          disabled={disabled}          aria-disabled={phase === "paying" || paid || undefined}          aria-label={paid ? `Paid ${money}` : phase === "failed" ? `${words.retry}: pay ${money}` : `Pay ${money}`}          onClick={pay}          className={`relative z-[1] block h-12 w-full cursor-pointer select-none overflow-clip rounded-full text-[15px] font-medium tracking-[-0.01em] disabled:cursor-default disabled:opacity-50 aria-disabled:cursor-default aria-disabled:active:scale-100 ${INTERACTION_PRESS} ${INTERACTION_FOCUS} ${            paid ? "bg-emerald-600 text-white" : "bg-primary text-primary-foreground"          }`}        >          <span aria-hidden="true" className={label("pay")} style={lineStyle("pay")}>            {labels?.pay ?? (              <span className="truncate">                Pay <NumberRoll value={amount} format={format} locales={locales} className="tabular-nums" />              </span>            )}          </span>          <span aria-hidden="true" className={label("retry")} style={lineStyle("retry")}>            <RotateCcw className="size-4 shrink-0" strokeWidth={2.25} />            <span className="truncate">{words.retry}</span>          </span>          <span aria-hidden="true" className={label("paying")} style={lineStyle("paying")}>            {method ? <CardGlyph /> : null}            <span className="truncate">              <span className="opacity-75">{words.paying}</span>              {card ? <span> {card}</span> : null}            </span>          </span>          <span aria-hidden="true" className={label("paid")} style={lineStyle("paid")}>            <svg viewBox="0 0 16 16" className="size-4 shrink-0">              <path                d="m3.2 8.4 3 3 6.6-6.8"                fill="none"                stroke="currentColor"                strokeWidth="2.2"                strokeLinecap="round"                strokeLinejoin="round"                pathLength={1}                style={{ strokeDasharray: 1, strokeDashoffset: paid ? 0 : 1, transition: reduced ? "none" : `stroke-dashoffset 340ms ease-out 200ms` }}              />            </svg>            <span className="truncate">              {words.paid} <span className="tabular-nums">{money}</span>            </span>          </span>        </button>      </div>      {/* The slot under the button: the receipt, or the reason it was declined. Its top stays tucked behind the button. */}      <div        className="grid"        inert={!open}        style={{ gridTemplateRows: open ? "1fr" : "0fr", marginTop: open ? -TUCK : 0, transition: slide === "none" ? "none" : `grid-template-rows ${slide}, margin-top ${slide}` }}      >        <div className="min-h-0 overflow-clip px-3">          <div            className="rounded-b-[16px] bg-background px-3.5 pb-3 text-[13px] shadow-[inset_0_0_0_1px_var(--border)]"            style={{ paddingTop: TUCK + 10, transform: open ? "none" : "translate3d(0,-100%,0)", transition: slide === "none" ? "none" : `transform ${slide}` }}          >            {note?.kind === "receipt" ? (              <dl className="grid gap-1.5">                {note.reference ? (                  <div className="flex h-6 items-center justify-between gap-3">                    <dt className="text-muted-foreground">Reference</dt>                    <dd className="flex min-w-0 items-center gap-1">                      <span className="truncate font-mono text-[12.5px] text-foreground">{note.reference}</span>                      <button                        type="button"                        onClick={copy}                        aria-label={copied ? "Copied" : "Copy reference"}                        className={`relative -mr-1.5 flex size-6 shrink-0 cursor-pointer items-center justify-center rounded-full text-muted-foreground hover:bg-accent hover:text-foreground ${INTERACTION_PRESS} ${INTERACTION_FOCUS}`}                      >                        <Copy                          aria-hidden="true"                          className="absolute size-3.5"                          style={{                            opacity: copied ? 0 : 1,                            transform: copied ? "scale(0.6)" : "none",                            filter: copied ? "blur(3px)" : "blur(0px)",                            transition: reduced ? "none" : `opacity 200ms ${EASE_OUT}, transform 260ms ${EASE_OUT}, filter 200ms ${EASE_OUT}`,                          }}                        />                        <Check                          aria-hidden="true"                          className="absolute size-3.5 text-emerald-600 dark:text-emerald-400"                          strokeWidth={2.5}                          style={{                            opacity: copied ? 1 : 0,                            transform: copied ? "none" : "scale(0.6)",                            filter: copied ? "blur(0px)" : "blur(3px)",                            transition: reduced ? "none" : `opacity 200ms ${EASE_OUT}, transform 260ms ${EASE_OUT}, filter 200ms ${EASE_OUT}`,                          }}                        />                      </button>                    </dd>                  </div>                ) : null}                <div className="flex h-6 items-center justify-between gap-3">                  <dt className="text-muted-foreground">{card ? "Charged to" : "Paid at"}</dt>                  <dd className="truncate tabular-nums text-foreground">{card ? `${card} · ${time}` : time}</dd>                </div>              </dl>            ) : note?.kind === "error" ? (              <p className="flex min-h-6 items-center gap-2 text-red-600 dark:text-red-400">                <svg aria-hidden="true" viewBox="0 0 16 16" className="size-4 shrink-0">                  <circle cx="8" cy="8" r="6.5" fill="none" stroke="currentColor" strokeWidth="1.5" />                  <path d="M8 4.75v3.75M8 11.1v.15" stroke="currentColor" strokeWidth="1.6" strokeLinecap="round" />                </svg>                <span className="min-w-0">{note.message}</span>              </p>            ) : null}          </div>        </div>      </div>      <span role="status" className="sr-only">        {announce}      </span>    </div>  );}export default PayButton;

Registry item: /r/pay-button.json