FreePress
Loading Button
A submit button that handles its own async state: return a Promise from onClick and it goes loading, then success with a drawn check or error with a retry label, and resets after a delay.
When to use it
- Subscribe, pay, apply coupon or save buttons that call an API
- Any form submit where people press twice because nothing seemed to happen
Watch out
- The success check is the whole confirmation; do not add a celebration on top
- Pass state yourself if the result arrives through a websocket or polling instead of the click Promise
Let your agent add it
One copy holds the install command, when to use it, the props and the design rules. Paste it into Claude Code, Cursor or Codex.
Install with the CLI
Uses the shadcn CLI. The source is copied into your project, so you own every line.
$ npx shadcn@latest add https://sunui.synvize.com/r/loading-button.jsonOr install manually
- 1. Install the dependencies.
$ npm install clsx tailwind-merge framer-motion - 2. Add a
cnhelper atlib/utils.tsif you do not have one. Not using shadcn/ui? Also add sunui-theme.css for the colour tokens (how). Then copy the component.loading-button.tsx"use client"; import { AnimatePresence, motion, useReducedMotion } from "framer-motion"; import { useEffect, useRef, useState, type ButtonHTMLAttributes, type ReactNode } from "react"; import { cn } from "@/lib/utils"; /** Brand accent: follows the theme's --primary by default; buyers set --sunui-spot to use their own brand colour. Used only for selection, offers and current progress */ const spotFill = "bg-[color:var(--sunui-spot,var(--primary))] text-[color:var(--sunui-spot-foreground,var(--primary-foreground))]"; const springs = { snappy: { type: "spring", stiffness: 520, damping: 34 }, gentle: { type: "spring", stiffness: 240, damping: 30 }, } as const; export type LoadingButtonState = "idle" | "loading" | "success" | "error"; export interface LoadingButtonProps extends Omit<ButtonHTMLAttributes<HTMLButtonElement>, "onClick" | "children" | "onAnimationStart" | "onDrag" | "onDragStart" | "onDragEnd"> { children: ReactNode; /** When it returns a Promise, switches loading → success (resolve) or error (reject) automatically */ onClick?: () => unknown; /** Controlled state; when given, the component stops managing it itself */ state?: LoadingButtonState; successLabel?: ReactNode; errorLabel?: ReactNode; /** Text screen readers read while loading */ loadingLabel?: string; /** shrink: shrinks to a circle while loading; inline: keeps its width and the spinner appears before the text */ loadingStyle?: "shrink" | "inline"; /** Milliseconds before returning to idle after success or failure; 0 stays on the result */ resetAfter?: number; variant?: "primary" | "paper"; } function Spinner({ className }: { className?: string }) { return ( <svg viewBox="0 0 24 24" fill="none" className={cn("size-4 animate-spin", className)} aria-hidden="true"> <circle cx="12" cy="12" r="9" stroke="currentColor" strokeOpacity="0.25" strokeWidth="2" /> <path d="M21 12a9 9 0 0 0-9-9" stroke="currentColor" strokeWidth="2" strokeLinecap="round" /> </svg> ); } function Check({ reduce }: { reduce: boolean | null }) { return ( <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" className="size-4" aria-hidden="true"> <motion.path d="M5 12.5l4.5 4.5L19 7.5" initial={{ pathLength: reduce ? 1 : 0 }} animate={{ pathLength: 1 }} transition={{ duration: reduce ? 0 : 0.28, ease: "easeOut" }} /> </svg> ); } export function LoadingButton({ children, onClick, state: stateProp, successLabel = "Done", errorLabel = "Try again", loadingLabel = "Loading", loadingStyle = "shrink", resetAfter = 2000, variant = "primary", className, disabled, type = "button", ...rest }: LoadingButtonProps) { const reduce = useReducedMotion(); const [inner, setInner] = useState<LoadingButtonState>("idle"); const state = stateProp ?? inner; const alive = useRef(true); const timer = useRef<number | undefined>(undefined); useEffect(() => { alive.current = true; return () => { alive.current = false; window.clearTimeout(timer.current); }; }, []); useEffect(() => { if (stateProp !== undefined || resetAfter <= 0 || (state !== "success" && state !== "error")) return; timer.current = window.setTimeout(() => alive.current && setInner("idle"), resetAfter); return () => window.clearTimeout(timer.current); }, [state, stateProp, resetAfter]); const handle = async () => { if (state === "loading") return; const result = onClick?.(); if (stateProp !== undefined || !(result instanceof Promise)) return; setInner("loading"); try { await result; if (alive.current) setInner("success"); } catch { if (alive.current) setInner("error"); } }; const shrunk = loadingStyle === "shrink" && state === "loading"; const t = reduce ? { duration: 0 } : springs.gentle; const fade = reduce ? { duration: 0 } : { duration: 0.14 }; return ( <motion.button {...rest} type={type} layout={!reduce} transition={t} onClick={handle} disabled={disabled} aria-busy={state === "loading" || undefined} aria-disabled={state === "loading" || undefined} whileTap={reduce || state === "loading" ? undefined : { scale: 0.97 }} style={{ borderRadius: shrunk ? 999 : 6 }} className={cn( "relative inline-flex h-10 items-center justify-center overflow-hidden whitespace-nowrap text-sm font-medium outline-offset-2 focus-visible:outline-2 disabled:pointer-events-none disabled:opacity-50", shrunk ? "w-10 px-0" : "px-4", variant === "primary" && state !== "error" && spotFill, variant === "paper" && "border border-foreground/10 bg-card text-foreground", state === "error" && "bg-destructive text-white", className, )} > <AnimatePresence mode="popLayout" initial={false}> <motion.span key={shrunk ? "spin" : state} initial={{ opacity: 0, y: reduce ? 0 : 6 }} animate={{ opacity: 1, y: 0 }} exit={{ opacity: 0, y: reduce ? 0 : -6 }} transition={fade} className="inline-flex items-center gap-2" > {shrunk ? ( <Spinner /> ) : state === "loading" ? ( <> <Spinner /> {children} </> ) : state === "success" ? ( <> <Check reduce={reduce} /> {successLabel} </> ) : state === "error" ? ( errorLabel ) : ( children )} </motion.span> </AnimatePresence> <span className="sr-only" aria-live="polite"> {state === "loading" ? loadingLabel : state === "success" ? successLabel : state === "error" ? errorLabel : ""} </span> </motion.button> ); }
Similar blocks
- Pro





