Button
The shadcn/ui Button, upgraded with Motion: a width-stable loading state, tactile press feedback and reduced-motion support — plus six animated blocks built on top of it.
- Drop-in shadcn API
- Motion
- Keyboard & screen-reader friendly
- prefers-reduced-motion
"use client";
import * as React from "react";
import { Rocket, Send, Trash2 } from "lucide-react";
import { Button } from "@/components/ui/button";
function useFakeRequest(ms = 1800) {
const [loading, setLoading] = React.useState(false);
const run = () => {
setLoading(true);
setTimeout(() => setLoading(false), ms);
};
return [loading, run] as const;
}
export default function ButtonLoadingDemo() {
const [deploying, deploy] = useFakeRequest();
const [sending, send] = useFakeRequest();
const [deleting, remove] = useFakeRequest();
return (
<>
<Button loading={deploying} onClick={deploy}>
<Rocket />
Deploy
</Button>
<Button variant="secondary" loading={sending} loadingText="Sending…" onClick={send}>
<Send />
Send invite
</Button>
<Button variant="destructive" size="icon" aria-label="Delete" loading={deleting} onClick={remove}>
<Trash2 />
</Button>
</>
);
}Installation
$ npx shadcn@latest add https://duskui.com/r/button.json1. Install the dependencies.
npm install motion @radix-ui/react-slot class-variance-authority lucide-react2. Copy the source into
components/ui/button.tsx.button.tsx "use client"; import * as React from "react"; import { Slot } from "@radix-ui/react-slot"; import { cva, type VariantProps } from "class-variance-authority"; import { Loader2 } from "lucide-react"; import { AnimatePresence, motion, type Transition } from "motion/react"; import { cn } from "@/lib/utils"; /** * DuskUI Button — a drop-in upgrade of the shadcn/ui Button. * * Same API as shadcn (variant, size, asChild) plus: * - `loading`: crossfades content to a spinner WITHOUT changing the width. * The button stays focusable (aria-disabled + aria-busy) instead of being * `disabled`, so keyboard and screen-reader users don't lose their place. * - `loadingText`: optional label shown next to the spinner. * - A subtle press state (CSS only, so it also works with `asChild`). * - Respects `prefers-reduced-motion`. */ const buttonVariants = cva( [ "relative inline-flex shrink-0 items-center justify-center gap-2 whitespace-nowrap rounded-md text-sm font-medium select-none outline-none", "transition-[color,background-color,border-color,box-shadow,transform] duration-150 ease-out", "active:scale-[0.98] motion-reduce:transition-none motion-reduce:active:scale-100", "disabled:pointer-events-none disabled:opacity-50 aria-busy:cursor-wait", "focus-visible:border-ring focus-visible:ring-[3px] focus-visible:ring-ring/50", "aria-invalid:border-destructive aria-invalid:ring-destructive/20 dark:aria-invalid:ring-destructive/40", "[&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4", ], { variants: { variant: { default: "bg-primary text-primary-foreground shadow-xs hover:bg-primary/90", destructive: "bg-destructive text-white shadow-xs hover:bg-destructive/90 focus-visible:ring-destructive/20 dark:bg-destructive/60 dark:focus-visible:ring-destructive/40", outline: "border bg-background shadow-xs hover:bg-accent hover:text-accent-foreground dark:border-input dark:bg-input/30 dark:hover:bg-input/50", secondary: "bg-secondary text-secondary-foreground shadow-xs hover:bg-secondary/80", soft: "bg-primary/10 text-primary hover:bg-primary/20", ghost: "hover:bg-accent hover:text-accent-foreground dark:hover:bg-accent/50", link: "text-primary underline-offset-4 hover:underline active:scale-100", }, size: { default: "h-9 px-4 py-2", sm: "h-8 gap-1.5 px-3", lg: "h-10 px-6", icon: "size-9", "icon-sm": "size-8", "icon-lg": "size-10", }, }, defaultVariants: { variant: "default", size: "default", }, } ); const contentTransition: Transition = { duration: 0.18, ease: "easeOut", }; export interface ButtonProps extends React.ComponentProps<"button">, VariantProps<typeof buttonVariants> { /** Render the child element instead of a `<button>` (Radix Slot). Loading is not supported with `asChild`. */ asChild?: boolean; /** Show a spinner and block clicks. The button keeps its width. */ loading?: boolean; /** Optional text rendered next to the spinner while loading. */ loadingText?: React.ReactNode; /** Custom spinner icon. Receives a `className`. */ loaderIcon?: React.ComponentType<{ className?: string }>; } function Button({ className, variant, size, asChild = false, loading = false, loadingText, loaderIcon: LoaderIcon = Loader2, children, onClick, ...props }: ButtonProps) { const dataAttrs = { "data-slot": "button", "data-variant": variant ?? "default", "data-size": size ?? "default", }; if (asChild) { return ( <Slot {...dataAttrs} className={cn(buttonVariants({ variant, size, className }))} onClick={onClick} {...props} > {children} </Slot> ); } const handleClick: React.MouseEventHandler<HTMLButtonElement> = (event) => { if (loading) { event.preventDefault(); event.stopPropagation(); return; } onClick?.(event); }; return ( <button {...dataAttrs} data-loading={loading || undefined} aria-busy={loading || undefined} aria-disabled={loading || props.disabled || undefined} className={cn(buttonVariants({ variant, size, className }))} onClick={handleClick} {...props} > {/* Both layers share one grid cell, so the button never changes width. */} <span className="grid place-items-center [gap:inherit]"> <motion.span data-slot="button-content" className="col-start-1 row-start-1 inline-flex items-center justify-center [gap:inherit]" initial={false} animate={ loading ? { opacity: 0, y: -4 } : { opacity: 1, y: 0 } } transition={contentTransition} aria-hidden={loading || undefined} > {children} </motion.span> <AnimatePresence initial={false}> {loading && ( <motion.span key="loader" data-slot="button-loader" className="col-start-1 row-start-1 inline-flex items-center justify-center [gap:inherit]" initial={{ opacity: 0, y: 4 }} animate={{ opacity: 1, y: 0 }} exit={{ opacity: 0, y: 4 }} transition={contentTransition} > <LoaderIcon className="animate-spin" aria-hidden /> {loadingText ? ( <span>{loadingText}</span> ) : ( <span className="sr-only">Loading</span> )} </motion.span> )} </AnimatePresence> </span> </button> ); } /** Button with Motion props (`whileHover`, `animate`, variants…). Use it to build animated blocks. */ const MotionButton = motion.create(Button); type MotionButtonProps = Omit<React.ComponentProps<typeof MotionButton>, "children"> & { children?: React.ReactNode; }; export { Button, MotionButton, buttonVariants, type MotionButtonProps };
Already using shadcn/ui? This file replaces components/ui/button.tsx and keeps the same API, so existing buttons keep working.
Usage
import { Button } from "@/components/ui/button"
export function SaveButton() {
const [saving, setSaving] = React.useState(false)
return (
<Button loading={saving} onClick={() => setSaving(true)}>
Save
</Button>
)
}Examples
Variants
All six shadcn variants plus soft, a tinted primary for secondary actions that still need the brand color.
import { Button } from "@/components/ui/button";
export default function ButtonVariantsDemo() {
return (
<>
<Button>Default</Button>
<Button variant="secondary">Secondary</Button>
<Button variant="soft">Soft</Button>
<Button variant="outline">Outline</Button>
<Button variant="ghost">Ghost</Button>
<Button variant="destructive">Destructive</Button>
<Button variant="link">Link</Button>
</>
);
}Sizes
Text sizes sm, default, lg and square icon sizes. Always give icon-only buttons an aria-label.
import { Settings } from "lucide-react";
import { Button } from "@/components/ui/button";
export default function ButtonSizesDemo() {
return (
<>
<Button size="sm">Small</Button>
<Button>Default</Button>
<Button size="lg">Large</Button>
<Button size="icon-sm" variant="outline" aria-label="Settings">
<Settings />
</Button>
<Button size="icon" variant="outline" aria-label="Settings">
<Settings />
</Button>
<Button size="icon-lg" variant="outline" aria-label="Settings">
<Settings />
</Button>
</>
);
}With icons
Drop any Lucide icon in as a child. Icons are auto-sized, and a group class makes trailing arrows nudge on hover.
import { ArrowRight, Mail, Plus } from "lucide-react";
import { Button } from "@/components/ui/button";
export default function ButtonIconsDemo() {
return (
<>
<Button>
<Mail />
Send email
</Button>
<Button variant="outline">
<Plus />
New project
</Button>
<Button variant="secondary" className="group">
Continue
<ArrowRight className="transition-transform duration-200 group-hover:translate-x-0.5" />
</Button>
</>
);
}Loading
loading crossfades the label into a spinner without changing the width, so nothing around it jumps. Clicks are blocked, but the button stays focusable and announces aria-busy. Add loadingText to show a label next to the spinner.
"use client";
import * as React from "react";
import { Rocket, Send, Trash2 } from "lucide-react";
import { Button } from "@/components/ui/button";
function useFakeRequest(ms = 1800) {
const [loading, setLoading] = React.useState(false);
const run = () => {
setLoading(true);
setTimeout(() => setLoading(false), ms);
};
return [loading, run] as const;
}
export default function ButtonLoadingDemo() {
const [deploying, deploy] = useFakeRequest();
const [sending, send] = useFakeRequest();
const [deleting, remove] = useFakeRequest();
return (
<>
<Button loading={deploying} onClick={deploy}>
<Rocket />
Deploy
</Button>
<Button variant="secondary" loading={sending} loadingText="Sending…" onClick={send}>
<Send />
Send invite
</Button>
<Button variant="destructive" size="icon" aria-label="Delete" loading={deleting} onClick={remove}>
<Trash2 />
</Button>
</>
);
}As link
asChild merges the button styles onto its child, e.g. a Next.js Link.
import Link from "next/link";
import { ArrowUpRight } from "lucide-react";
import { Button } from "@/components/ui/button";
export default function ButtonAsChildDemo() {
return (
<Button asChild variant="outline">
<Link href="/components">
Browse components
<ArrowUpRight />
</Link>
</Button>
);
}Blocks
Ready-made variations composed from the base component with Motion. Each installs on its own and pulls in its dependencies automatically.
Status Button
Walks through idle → loading → success / error in place. The width eases between labels, the check mark draws itself and errors shake. Pair it with the useStatusAction hook to wire any async function.
"use client";
import * as React from "react";
import { Save } from "lucide-react";
import { StatusButton, useStatusAction } from "@/components/dusk/button/status-button";
const wait = (ms: number) => new Promise((r) => setTimeout(r, ms));
export default function StatusButtonDemo() {
const save = useStatusAction(() => wait(1400));
const flaky = useStatusAction(async () => {
await wait(1200);
throw new Error("Network error");
});
return (
<>
<StatusButton status={save.status} onClick={save.run}>
<Save />
Save changes
</StatusButton>
<StatusButton
variant="outline"
status={flaky.status}
onClick={flaky.run}
labels={{ loading: "Publishing", error: "Failed — retry" }}
>
Publish (fails)
</StatusButton>
</>
);
}$ npx shadcn@latest add https://duskui.com/r/status-button.json1. Install the dependencies.
npm install motion lucide-react2. Copy the source into
components/dusk/button/status-button.tsx.status-button.tsx "use client"; import * as React from "react"; import { AnimatePresence, motion, useAnimate } from "motion/react"; import { Loader2, X } from "lucide-react"; import { Button, type ButtonProps } from "@/components/ui/button"; import { cn } from "@/lib/utils"; export type ButtonStatus = "idle" | "loading" | "success" | "error"; export interface StatusButtonProps extends Omit<ButtonProps, "loading"> { status?: ButtonStatus; /** Labels for each non-idle state. Idle shows `children`. */ labels?: Partial<Record<Exclude<ButtonStatus, "idle">, React.ReactNode>>; } const defaultLabels = { loading: "Saving", success: "Saved", error: "Try again", } as const; const swap = { initial: { opacity: 0, y: 8 }, animate: { opacity: 1, y: 0 }, exit: { opacity: 0, y: -8 }, transition: { type: "spring", duration: 0.25, bounce: 0 }, } as const; function AnimatedCheck() { return ( <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth={2.5} strokeLinecap="round" strokeLinejoin="round" aria-hidden> <motion.path d="M4 12.5l5 5L20 6.5" initial={{ pathLength: 0 }} animate={{ pathLength: 1 }} transition={{ duration: 0.35, delay: 0.1, ease: "easeOut" }} /> </svg> ); } /** Measures an element's width so the button can animate between label sizes. */ function useWidth<T extends HTMLElement>() { const ref = React.useRef<T>(null); const [width, setWidth] = React.useState<number>(); React.useLayoutEffect(() => { const el = ref.current; if (!el) return; const observer = new ResizeObserver(([entry]) => setWidth(entry.borderBoxSize?.[0]?.inlineSize ?? el.offsetWidth) ); observer.observe(el); return () => observer.disconnect(); }, []); return [ref, width] as const; } /** * One button that walks through idle → loading → success / error. * The width eases between labels, the success check draws itself and * errors give a short shake. Status changes are announced to screen readers. */ export function StatusButton({ status = "idle", labels, className, children, onClick, ...props }: StatusButtonProps) { const [scope, animate] = useAnimate<HTMLSpanElement>(); const [measureRef, width] = useWidth<HTMLSpanElement>(); const text = { ...defaultLabels, ...labels }; React.useEffect(() => { if (status === "error" && scope.current) { animate(scope.current, { x: [0, -5, 5, -3, 3, 0] }, { duration: 0.4 }); } }, [status, animate, scope]); const content: Record<ButtonStatus, React.ReactNode> = { idle: children, loading: ( <> <Loader2 className="animate-spin" aria-hidden /> {text.loading} </> ), success: ( <> <AnimatedCheck /> {text.success} </> ), error: ( <> <X aria-hidden /> {text.error} </> ), }; return ( <Button aria-busy={status === "loading" || undefined} aria-disabled={status === "loading" || undefined} onClick={(event) => { if (status === "loading") return event.preventDefault(); onClick?.(event); }} className={cn( "overflow-hidden", // dark: + border overrides so the state colors win over every variant. status === "success" && "border-transparent bg-emerald-500 text-white hover:bg-emerald-500/90 dark:bg-emerald-500 dark:hover:bg-emerald-500/90", status === "error" && "border-transparent bg-destructive text-white hover:bg-destructive/90 dark:bg-destructive dark:hover:bg-destructive/90", className )} {...props} > <motion.span ref={scope} className="inline-flex justify-center" initial={false} animate={{ width: width ?? "auto" }} transition={{ type: "spring", duration: 0.3, bounce: 0 }} > <span ref={measureRef} aria-live="polite" className="relative inline-flex items-center whitespace-nowrap"> <AnimatePresence mode="popLayout" initial={false}> <motion.span key={status} className="inline-flex items-center gap-2" {...swap}> {content[status]} </motion.span> </AnimatePresence> </span> </motion.span> </Button> ); } /** * Wires an async action to a StatusButton. * `const { status, run } = useStatusAction(save)` → `<StatusButton status={status} onClick={run} />` */ export function useStatusAction<T>( action: () => Promise<T>, { resetAfter = 1800 }: { resetAfter?: number } = {} ) { const [status, setStatus] = React.useState<ButtonStatus>("idle"); const timer = React.useRef<ReturnType<typeof setTimeout>>(undefined); React.useEffect(() => () => clearTimeout(timer.current), []); const run = React.useCallback(async () => { clearTimeout(timer.current); setStatus("loading"); try { const result = await action(); setStatus("success"); return result; } catch { setStatus("error"); return undefined; } finally { timer.current = setTimeout(() => setStatus("idle"), resetAfter); } }, [action, resetAfter]); return { status, run, setStatus }; }
| Prop | Type | Default | Description |
|---|---|---|---|
| status | "idle" | "loading" | "success" | "error" | "idle" | Current state. Idle renders children. |
| labels | Partial<Record<status, ReactNode>> | Saving / Saved / Try again | Labels for the non-idle states. |
Hold to Confirm
A safer alternative to a confirm dialog for destructive actions. A fill wipes across while held; releasing early springs it back. Works with mouse, touch, Space and Enter.
"use client";
import * as React from "react";
import { Trash2 } from "lucide-react";
import { toast } from "sonner";
import { HoldToConfirmButton } from "@/components/dusk/button/hold-to-confirm-button";
export default function HoldToConfirmDemo() {
return (
<HoldToConfirmButton
size="lg"
className="text-destructive"
onConfirm={() => toast.success("Project deleted")}
>
<Trash2 />
Hold to delete
</HoldToConfirmButton>
);
}$ npx shadcn@latest add https://duskui.com/r/hold-to-confirm-button.json1. Install the dependencies.
npm install motion2. Copy the source into
components/dusk/button/hold-to-confirm-button.tsx.hold-to-confirm-button.tsx "use client"; import * as React from "react"; import { animate, motion, useMotionTemplate, useMotionValue, useTransform, type AnimationPlaybackControls, } from "motion/react"; import { Button, type ButtonProps } from "@/components/ui/button"; import { cn } from "@/lib/utils"; export interface HoldToConfirmButtonProps extends Omit<ButtonProps, "onClick"> { /** Fired once the hold completes. */ onConfirm: () => void; /** How long the user must hold, in ms. */ holdDuration?: number; /** Classes for the fill layer that wipes in while holding. */ fillClassName?: string; } /** * Press and hold to confirm a destructive action. Releasing early springs * the progress back. Works with mouse, touch, and Space / Enter. */ export function HoldToConfirmButton({ onConfirm, holdDuration = 1200, variant = "outline", className, fillClassName = "bg-[color-mix(in_oklab,var(--color-destructive)_70%,black)] text-white", children, disabled, ...props }: HoldToConfirmButtonProps) { const progress = useMotionValue(0); const remaining = useTransform(progress, (v) => (1 - v) * 100); const clipPath = useMotionTemplate`inset(0 ${remaining}% 0 0)`; const controls = React.useRef<AnimationPlaybackControls | null>(null); const done = React.useRef(false); React.useEffect(() => () => controls.current?.stop(), []); const start = () => { if (disabled) return; done.current = false; controls.current?.stop(); controls.current = animate(progress, 1, { duration: (holdDuration / 1000) * (1 - progress.get()), ease: "linear", onComplete: () => { done.current = true; onConfirm(); controls.current = animate(progress, 0, { delay: 0.6, duration: 0.3 }); }, }); }; const cancel = () => { if (done.current) return; controls.current?.stop(); controls.current = animate(progress, 0, { type: "spring", duration: 0.4, bounce: 0 }); }; const isActivationKey = (event: React.KeyboardEvent) => event.key === " " || event.key === "Enter"; return ( <Button variant={variant} disabled={disabled} className={cn("overflow-hidden touch-none", className)} onPointerDown={(event) => { if (event.button === 0) start(); }} onPointerUp={cancel} onPointerLeave={cancel} onPointerCancel={cancel} onKeyDown={(event) => { if (!isActivationKey(event)) return; event.preventDefault(); if (!event.repeat) start(); }} onKeyUp={(event) => { if (isActivationKey(event)) cancel(); }} onContextMenu={(event) => event.preventDefault()} {...props} > {children} <span className="sr-only"> (press and hold to confirm)</span> {/* Same label in the fill colors, revealed left → right. */} <motion.span aria-hidden className={cn( "pointer-events-none absolute inset-0 inline-flex items-center justify-center [gap:inherit]", fillClassName )} style={{ clipPath }} > {children} </motion.span> </Button> ); }
| Prop | Type | Default | Description |
|---|---|---|---|
| onConfirm | () => void | — | Called once the hold completes. |
| holdDuration | number | 1200 | Hold time in milliseconds. |
| fillClassName | string | "bg-[color-mix(…destructive 70%, black)] text-white" | Classes for the fill layer. The default darkens the destructive color so white text stays readable. |
Shimmer Button
A thin, faint sheen sweeps across on hover, or on a slow loop with idle. Best kept to one primary call to action per screen.
import { ShimmerButton } from "@/components/dusk/button/shimmer-button";
export default function ShimmerButtonDemo() {
return (
<>
<ShimmerButton size="lg">Upgrade to Pro</ShimmerButton>
<ShimmerButton size="lg" variant="secondary" idle>
Start free trial
</ShimmerButton>
</>
);
}$ npx shadcn@latest add https://duskui.com/r/shimmer-button.json1. Install the dependencies.
npm install motion2. Copy the source into
components/dusk/button/shimmer-button.tsx.shimmer-button.tsx "use client"; import * as React from "react"; import { motion, useReducedMotion, type Variants } from "motion/react"; import { MotionButton, type MotionButtonProps } from "@/components/ui/button"; import { cn } from "@/lib/utils"; export interface ShimmerButtonProps extends MotionButtonProps { /** Keep a slow shimmer sweeping while idle, not only on hover. */ idle?: boolean; /** Seconds to wait between idle sweeps. */ interval?: number; } const sheen: Variants = { rest: { x: "-110%", transition: { duration: 0 } }, hover: { x: "110%", transition: { duration: 0.8, ease: [0.4, 0, 0.2, 1] } }, }; /** * A thin, faint sheen sweeps across the button on hover (and optionally on a loop). * Good for a single primary call-to-action per screen. */ export function ShimmerButton({ className, children, idle = false, interval = 4, ...props }: ShimmerButtonProps) { const reduceMotion = useReducedMotion(); return ( <MotionButton initial="rest" animate="rest" whileHover="hover" className={cn("overflow-hidden", className)} {...props} > {!reduceMotion && ( <motion.span aria-hidden className="pointer-events-none absolute inset-0 -skew-x-12 bg-[linear-gradient(90deg,transparent_42%,rgb(255_255_255/0.3)_50%,transparent_58%)] mix-blend-overlay" {...(idle ? { initial: { x: "-110%" }, animate: { x: ["-110%", "110%"] }, transition: { duration: 1.2, ease: "easeInOut", repeat: Infinity, repeatDelay: interval, }, } : { variants: sheen })} /> )} {children} </MotionButton> ); }
| Prop | Type | Default | Description |
|---|---|---|---|
| idle | boolean | false | Sweep on a loop instead of only on hover. |
| interval | number | 4 | Seconds between idle sweeps. |
Magnetic Button
Pulled slightly toward the cursor on a damped spring, with the label moving slightly further for depth. Mouse only; static for touch and reduced motion.
import { ArrowRight } from "lucide-react";
import { MagneticButton } from "@/components/dusk/button/magnetic-button";
export default function MagneticButtonDemo() {
return (
<MagneticButton size="lg">
Get started
<ArrowRight />
</MagneticButton>
);
}$ npx shadcn@latest add https://duskui.com/r/magnetic-button.json1. Install the dependencies.
npm install motion2. Copy the source into
components/dusk/button/magnetic-button.tsx.magnetic-button.tsx "use client"; import * as React from "react"; import { motion, useMotionValue, useReducedMotion, useSpring, useTransform, } from "motion/react"; import { MotionButton, type MotionButtonProps } from "@/components/ui/button"; export interface MagneticButtonProps extends MotionButtonProps { /** How strongly the button follows the cursor (0–1). */ strength?: number; } const spring = { stiffness: 220, damping: 24, mass: 0.5 }; /** * The button is pulled slightly toward the cursor and eases back on leave. * The label moves a touch further than the surface for a parallax feel. * Only reacts to a mouse, never to touch, and is static with reduced motion. */ export function MagneticButton({ strength = 0.15, children, onPointerMove, onPointerLeave, ...props }: MagneticButtonProps) { const reduceMotion = useReducedMotion(); const x = useMotionValue(0); const y = useMotionValue(0); const springX = useSpring(x, spring); const springY = useSpring(y, spring); const labelX = useTransform(springX, (v) => v * 0.3); const labelY = useTransform(springY, (v) => v * 0.3); const handleMove = (event: React.PointerEvent<HTMLButtonElement>) => { onPointerMove?.(event); if (reduceMotion || event.pointerType !== "mouse") return; const rect = event.currentTarget.getBoundingClientRect(); x.set((event.clientX - (rect.left + rect.width / 2)) * strength); y.set((event.clientY - (rect.top + rect.height / 2)) * strength); }; const handleLeave = (event: React.PointerEvent<HTMLButtonElement>) => { onPointerLeave?.(event); x.set(0); y.set(0); }; return ( <MotionButton style={{ x: springX, y: springY }} onPointerMove={handleMove} onPointerLeave={handleLeave} {...props} > <motion.span className="inline-flex items-center [gap:inherit]" style={{ x: labelX, y: labelY }} > {children} </motion.span> </MotionButton> ); }
| Prop | Type | Default | Description |
|---|---|---|---|
| strength | number | 0.15 | How far the button follows the cursor (0–1). |
Spotlight Button
A faint highlight tracks the cursor along the 1px border, with a barely visible tint on the surface. Uses motion values, so moving the mouse never re-renders React.
import { Github } from "lucide-react";
import { SpotlightButton } from "@/components/dusk/button/spotlight-button";
export default function SpotlightButtonDemo() {
return (
<>
<SpotlightButton size="lg">
<Github />
Star on GitHub
</SpotlightButton>
<SpotlightButton size="lg" radius={48}>
Read the docs
</SpotlightButton>
</>
);
}$ npx shadcn@latest add https://duskui.com/r/spotlight-button.json1. Install the dependencies.
npm install motion2. Copy the source into
components/dusk/button/spotlight-button.tsx.spotlight-button.tsx "use client"; import * as React from "react"; import { motion, useMotionTemplate, useMotionValue } from "motion/react"; import { Button, type ButtonProps } from "@/components/ui/button"; import { cn } from "@/lib/utils"; export interface SpotlightButtonProps extends ButtonProps { /** Radius of the light in px. */ radius?: number; /** Any CSS color. Mixed in at low opacity; defaults to white. */ color?: string; } /** * A faint highlight follows the cursor along the 1px border, with a barely * visible tint on the surface. Pairs well with `variant="outline"` on dark * backgrounds. */ export function SpotlightButton({ radius = 60, color = "#ffffff", variant = "outline", className, children, onPointerMove, ...props }: SpotlightButtonProps) { const x = useMotionValue(-radius * 2); const y = useMotionValue(-radius * 2); const border = useMotionTemplate`radial-gradient(${radius}px circle at ${x}px ${y}px, color-mix(in oklab, ${color} 35%, transparent), transparent 70%)`; const fill = useMotionTemplate`radial-gradient(${radius}px circle at ${x}px ${y}px, color-mix(in oklab, ${color} 4%, transparent), transparent 70%)`; const handleMove = (event: React.PointerEvent<HTMLButtonElement>) => { onPointerMove?.(event); const rect = event.currentTarget.getBoundingClientRect(); x.set(event.clientX - rect.left); y.set(event.clientY - rect.top); }; const layer = "pointer-events-none absolute inset-0 rounded-[inherit] opacity-0 transition-opacity duration-200 group-hover/spotlight:opacity-100 group-focus-visible/spotlight:opacity-100"; return ( <Button variant={variant} className={cn("group/spotlight", className)} onPointerMove={handleMove} {...props} > {/* Border light: the gradient is masked to a 1px ring. */} <motion.span aria-hidden className={cn( layer, "p-px [mask-image:linear-gradient(#000_0_0),linear-gradient(#000_0_0)] [mask-clip:content-box,border-box] [mask-composite:exclude]" )} style={{ background: border }} /> <motion.span aria-hidden className={layer} style={{ background: fill }} /> {children} </Button> ); }
| Prop | Type | Default | Description |
|---|---|---|---|
| radius | number | 60 | Radius of the light in px. |
| color | string | "#ffffff" | Any CSS color, mixed in at low opacity. |
Copy Button
Copies text and morphs the icon into a check mark. It powers every copy button in these docs.
import { CopyButton } from "@/components/dusk/button/copy-button";
export default function CopyButtonDemo() {
const command = "npx shadcn@latest add https://duskui.com/r/button.json";
return (
<div className="flex max-w-full items-center gap-2 rounded-lg border border-white/10 bg-zinc-950 py-1 pl-4 pr-1 font-mono text-sm text-white/80">
<span className="truncate">{command}</span>
<CopyButton value={command} />
</div>
);
}$ npx shadcn@latest add https://duskui.com/r/copy-button.json1. Install the dependencies.
npm install motion lucide-react2. Copy the source into
components/dusk/button/copy-button.tsx.copy-button.tsx "use client"; import * as React from "react"; import { AnimatePresence, motion } from "motion/react"; import { Check, Copy } from "lucide-react"; import { Button, type ButtonProps } from "@/components/ui/button"; export interface CopyButtonProps extends Omit<ButtonProps, "value"> { /** Text written to the clipboard. */ value: string; /** Called after a successful copy. */ onCopied?: (value: string) => void; /** How long the success state stays visible, in ms. */ timeout?: number; } const iconMotion = { initial: { opacity: 0, scale: 0.6 }, animate: { opacity: 1, scale: 1 }, exit: { opacity: 0, scale: 0.6 }, transition: { type: "spring", duration: 0.2, bounce: 0 }, } as const; /** Icon button that copies text and morphs its icon into a check mark. */ export function CopyButton({ value, onCopied, timeout = 1600, variant = "ghost", size = "icon-sm", children, onClick, ...props }: CopyButtonProps) { const [copied, setCopied] = React.useState(false); const timer = React.useRef<ReturnType<typeof setTimeout>>(undefined); React.useEffect(() => () => clearTimeout(timer.current), []); const handleClick = async (event: React.MouseEvent<HTMLButtonElement>) => { onClick?.(event); try { await navigator.clipboard.writeText(value); setCopied(true); onCopied?.(value); clearTimeout(timer.current); timer.current = setTimeout(() => setCopied(false), timeout); } catch { setCopied(false); } }; return ( <Button variant={variant} size={size} aria-label={copied ? "Copied" : "Copy to clipboard"} onClick={handleClick} {...props} > <span className="relative inline-flex"> <AnimatePresence mode="popLayout" initial={false}> {copied ? ( <motion.span key="check" className="inline-flex text-emerald-400" {...iconMotion}> <Check /> </motion.span> ) : ( <motion.span key="copy" className="inline-flex" {...iconMotion}> <Copy /> </motion.span> )} </AnimatePresence> </span> {children} </Button> ); }
| Prop | Type | Default | Description |
|---|---|---|---|
| value | string | — | Text written to the clipboard. |
| onCopied | (value: string) => void | — | Called after a successful copy. |
| timeout | number | 1600 | How long the check stays, in ms. |
API Reference
Accepts every native <button> prop. Also exports MotionButton (the Button with Motion props) and buttonVariants for styling other elements.
| Prop | Type | Default | Description |
|---|---|---|---|
| variant | "default" | "secondary" | "soft" | "outline" | "ghost" | "destructive" | "link" | "default" | Visual style. |
| size | "sm" | "default" | "lg" | "icon" | "icon-sm" | "icon-lg" | "default" | Height and padding. |
| loading | boolean | false | Shows a spinner, blocks clicks, keeps width and focus. |
| loadingText | ReactNode | — | Optional label next to the spinner. |
| loaderIcon | ComponentType<{ className?: string }> | Loader2 | Custom spinner icon. |
| asChild | boolean | false | Render the child element instead (Radix Slot). Loading is ignored. |
Accessibility
- While loading the button uses
aria-disabledandaria-busyinstead ofdisabled, so focus is never lost. - The spinner has a screen-reader label; status changes in Status Button are announced with
aria-live. - Visible focus ring on keyboard focus only (
focus-visible). - Movement is removed when the user prefers reduced motion; opacity fades remain.