Engineering
React Copy to Clipboard Button for shadcn/ui
Build a React copy-to-clipboard button for shadcn/ui with async text resolvers, Safari ClipboardItem support, error states, screen-reader feedback, and motion.
A React copy-to-clipboard button looks like a five-line navigator.clipboard.writeText
handler until it ships to real users. Then Safari rejects async text because the
user gesture expired during a fetch, a staging URL on plain HTTP throws
because navigator.clipboard is undefined outside secure contexts, rapid
clicks race the reset timer, and screen-reader users get no confirmation that
anything happened.
TentUI's Copy Button is a free and source-available
shadcn/ui component that models copying as three explicit states (idle,
done, error), supports synchronous and async text resolvers without losing
Safari's user-gesture context, swaps icons cleanly through IconSwap, and pairs
visual confirmation with UI sounds and haptics.
Click the button to copy the command, watch the copy icon transition into a check icon, and wait 1.5 seconds for it to settle back to idle.
Quick start
Add the @tentui registry to components.json (see the
installation guide), then install Copy Button with the
shadcn CLI:
pnpm dlx shadcn@latest add @tentui/copy-button
The CLI installs the shadcn button primitive plus motion, lucide-react,
web-haptics, and @rexa-developer/tiks, and copies three editable files into
your repository:
components/copy-button.tsx— the button wrapper andCopyStateIconcomponents/icon-swap/icon-swap.tsx— the spring-basedAnimatePresenceicon swapperhooks/use-copy-to-clipboard.ts— the reusable clipboard state machine
Use it with static text or a label:
"use client";
import { CopyButton } from "@/components/copy-button";
export function InstallCommandCopy() {
return (
<CopyButton
size="default"
variant="outline"
text="npx shadcn@latest add @tentui/copy-button"
>
Copy command
</CopyButton>
);
}Lazy and async text resolvers without breaking Safari
Often the string you need to copy is not ready at render time: you might read
window.location.href at click time, serialize a canvas or Markdown document,
or fetch a signed invite link from an API endpoint.
If you await fetch(...) first and then call navigator.clipboard.writeText(value),
Safari frequently throws NotAllowedError because the awaited network request
breaks Safari's strict user-activation window.
use-copy-to-clipboard.ts avoids that failure by accepting
CopyText = string | (() => string | Promise<string>) and passing async
Promises directly inside a ClipboardItem:
export type CopyText = string | (() => string | Promise<string>);
async function writeClipboard(text: CopyText) {
const value = typeof text === "function" ? text() : text;
if (typeof value === "string") {
await navigator.clipboard.writeText(value);
return value;
}
const blob = value.then((v) => new Blob([v], { type: "text/plain" }));
await navigator.clipboard.write([new ClipboardItem({ "text/plain": blob })]);
return value;
}Because navigator.clipboard.write(...) is called synchronously inside the click
handler with a Promise<Blob>, Safari preserves the user-gesture token while
your async resolver finishes. That lets you write clean click-time resolvers:
<CopyButton
aria-label="Copy invite link"
text={async () => {
const res = await fetch("/api/invite-link", { method: "POST" });
if (!res.ok) throw new Error("Failed to generate invite link");
const data = (await res.json()) as { url: string };
return data.url;
}}
/>For longer async operations where you need a visible spinner and duplicate-click
locking while a server request runs, use Stateful Button
instead—the shadcn loading button guide covers
that four-state (idle, loading, success, error) lifecycle in detail.
Handle clipboard failures honestly (error state)
Assuming every copy succeeds creates silent frustration when the browser blocks clipboard access. Common real-world failure cases include:
| Failure scenario | What happens in the browser | How useCopyToClipboard responds |
|---|---|---|
Non-HTTPS page (e.g. LAN IP http://192.168.x.x) | navigator.clipboard is undefined outside secure contexts (https: or localhost) | Enters error state, plays error sound/haptic, fires onCopyError |
Embedded <iframe> without allow="clipboard-write" | writeText / write rejects with NotAllowedError | Enters error state and passes the error to onCopyError |
Dynamic text() resolver throws or rejects | Rejected Promise caught in try/catch | Enters error state, shows errorIcon (CircleXIcon), resets after resetDelay |
| Rapid repeated clicks | Previous timeout would prematurely clear the new state | Clears resetTimeoutRef.current before every attempt and cleans up on unmount |
Every failure transitions CopyState to "error", swaps the icon to
CircleXIcon (customizable via errorIcon), triggers error haptics and sound,
and invokes onCopyError(error) so you can log the error or offer a fallback
dialog with selectable text. After resetDelay (default 1500 ms), the timer
returns the button to "idle".
Icon transitions and reduced motion
Swapping icons by mounting and unmounting with no transition can feel abrupt,
while animating width causes adjacent toolbar buttons to jitter. CopyStateIcon
wraps the active icon in IconSwap (AnimatePresence mode="popLayout" initial={false}),
keyed by state:
export function IconSwapItem({
as: Component = motion.div,
...props
}: HTMLMotionProps<"div"> & { as?: typeof motion.div | typeof motion.span }) {
return (
<Component
initial={{ opacity: 0, scale: 0.25, filter: "blur(4px)" }}
animate={{ opacity: 1, scale: 1, filter: "blur(0px)" }}
exit={{ opacity: 0, scale: 0.25, filter: "blur(4px)" }}
transition={{ type: "spring", duration: 0.3, bounce: 0 }}
{...props}
/>
);
}Because mode="popLayout" takes exiting icons out of layout flow immediately,
the button's width never shifts when CopyIcon swaps to CheckIcon or
CircleXIcon.
For reduced motion, wrap your app (or the button subtree) in Motion's
<MotionConfig reducedMotion="user">. With reducedMotion="user" enabled,
Motion suppresses transform/scale motion while keeping the icon swap visible.
Because icon-swap.tsx lives in your own codebase, you can also inspect
useReducedMotion() inside IconSwapItem if you want to strip filter: blur(...)
under reduced motion as well.
Screen-reader announcements and accessible naming
CopyButton renders your local shadcn <Button> (a native <button>), so
keyboard focus, Enter, and Space activation work out of the box. Two
accessibility details deserve explicit attention in your integration:
- Be specific with
aria-label.CopyButtondefaults toaria-label="Copy". When a page has multiple icon-only copy buttons (for example, next to an API key, webhook secret, and install command), pass a distinct label such asaria-label="Copy webhook secret". When you render visible child text likeCopy command, either omitaria-labelin your copied source or matcharia-labelto the visible text so voice-control users can activate it by name. - Add a polite live region when confirmation matters. Out of the box,
CopyButtonkeeps its feedback visual, auditory, and tactile. Because you owncopy-button.tsx, adding a screen-reader status announcement takes three lines alongside the button:
<span className="sr-only" role="status" aria-live="polite">
{state === "done" ? "Copied to clipboard" : state === "error" ? "Copy failed" : ""}
</span>Keep the live region mounted in the DOM at all times and toggle only its text
content—dynamically mounting a role="status" element on click is inconsistently
announced across VoiceOver and NVDA.
Composing Copy Button in larger menus
Copy controls rarely live in isolation. In TentUI, Brand Context Menu
composes clipboard copy actions inside a right-click context menu for copying
SVG marks and wordmarks alongside ZIP downloads. Because useCopyToClipboard
is exported as its own hook (hooks/use-copy-to-clipboard.ts), you can reuse
the exact same Safari-safe async write, error handling, timer cleanup, and
haptic feedback inside menu items, command palettes, or keyboard shortcuts
without rendering a separate CopyButton.
Inspect the installed source
Here is the complete CopyButton component that npx shadcn@latest add @tentui/copy-button
copies into your project:
"use client";
import { CheckIcon, CircleXIcon, CopyIcon } from "lucide-react";
import { motion } from "motion/react";
import type { ComponentProps } from "react";
import { Button } from "@/components/ui/button";
import type { CopyState, CopyText } from "@/hooks/use-copy-to-clipboard";
import { useCopyToClipboard } from "@/hooks/use-copy-to-clipboard";
import { cn } from "@/lib/utils";
import {
IconSwap,
IconSwapItem,
} from "@/components/icon-swap/icon-swap";
export type CopyStateIconProps = {
state: CopyState;
/** Custom icon for idle state. */
idleIcon?: React.ReactNode;
/** Custom icon for done state. */
doneIcon?: React.ReactNode;
/** Custom icon for error state. */
errorIcon?: React.ReactNode;
};
export function CopyStateIcon({
state,
idleIcon,
doneIcon,
errorIcon,
}: CopyStateIconProps) {
let icon = idleIcon ?? (
<CopyIcon data-icon="inline-start" data-slot="idle-icon" />
);
if (state === "done") {
icon = doneIcon ?? (
<CheckIcon data-icon="inline-start" data-slot="done-icon" />
);
} else if (state === "error") {
icon = errorIcon ?? (
<CircleXIcon data-icon="inline-start" data-slot="error-icon" />
);
}
return (
<IconSwap>
<IconSwapItem key={state} as={motion.span}>
{icon}
</IconSwapItem>
</IconSwap>
);
}
export type CopyButtonProps = ComponentProps<typeof Button> & {
/** The text to copy, or a function that returns the text. */
text: CopyText;
/** Called with the copied text on successful copy. */
onCopySuccess?: (text: string) => void;
/** Called with the error if the copy operation fails. */
onCopyError?: (error: Error) => void;
} & Omit<CopyStateIconProps, "state">;
export function CopyButton({
className,
size = "icon",
children,
text,
idleIcon,
doneIcon,
errorIcon,
onClick,
onCopySuccess,
onCopyError,
...props
}: CopyButtonProps) {
const { state, copy } = useCopyToClipboard({
onCopySuccess,
onCopyError,
});
return (
<Button
className={cn("will-change-transform", className)}
size={size}
onClick={(e) => {
void copy(text);
onClick?.(e);
}}
aria-label="Copy"
{...props}
>
<CopyStateIcon
state={state}
idleIcon={idleIcon}
doneIcon={doneIcon}
errorIcon={errorIcon}
/>
{children}
</Button>
);
}
export default CopyButton;Because it builds directly on your project's shadcn Button, it inherits your
existing variant, size, radius, and focus-ring tokens automatically.
FAQ
How do I install a copy-to-clipboard button in shadcn/ui?
Add "@tentui": "https://tentui.com/r/{name}.json" to components.json and run npx shadcn@latest add @tentui/copy-button, or install directly from https://tentui.com/r/copy-button.json. The CLI copies copy-button.tsx, icon-swap.tsx, and use-copy-to-clipboard.ts into your project and installs the shadcn button plus motion, lucide-react, web-haptics, and @rexa-developer/tiks.
How do I copy asynchronously fetched text without Safari blocking it?
Pass an async function to the text prop (text={async () => fetchToken()}). useCopyToClipboard passes the unresolved Promise into a new ClipboardItem({ "text/plain": blob }) call synchronously during the click event so Safari preserves the user-gesture context while the Promise resolves.
Why does navigator.clipboard fail on some staging or local URLs?
Browsers restrict the async Clipboard API to secure contexts (https:// or http://localhost). Opening a preview on plain http:// over a LAN IP—or inside a cross-origin <iframe> without allow="clipboard-write"—causes clipboard writes to fail, which CopyButton surfaces through its error state and onCopyError callback.
Does the Copy Button announce copied status to screen readers?
Out of the box, CopyButton provides native button semantics (aria-label="Copy") with visual, sound, and haptic feedback. Because the component source lives in your project, you can add a persistent <span className="sr-only" role="status" aria-live="polite"> driven by state when assistive-technology confirmation is required.
How do I customize the icons, reset duration, or button styling?
Pass idleIcon, doneIcon, and errorIcon to swap any Lucide icon, and pass standard shadcn Button props such as variant, size, or className. To change the 1.5-second reset delay or turn off sound and haptics, edit resetDelay or remove the useTiks / useWebHaptics calls directly in hooks/use-copy-to-clipboard.ts.
Is the Copy Button free to use in commercial projects?
Yes. TentUI's Copy Button is free and source-available: you can copy, modify, and ship it in unlimited personal and client projects under the TentUI License, though you may not redistribute or resell the component itself.
Components in this guide
All componentsCopy Button
Copy text to the clipboard with visual, sound, and haptic feedback.
npx shadcn@latest add @tentui/copy-buttonStateful Button
Communicate async loading, success, and error states without leaving the button.
npx shadcn@latest add @tentui/stateful-buttonBrand Context Menu
Share copy-ready and downloadable brand assets from a contextual menu.
npx shadcn@latest add @tentui/brand-context-menu
Related guides
All posts- Best Animated shadcn/ui Components in 2026
A guide to TentUI's animated shadcn/ui components by job, from async buttons and pickers to charts, overlays, text effects, and AI thinking UI.
- How to Add Animations to shadcn Components
Build accessible shadcn animations with source-owned code, shared-layout transitions, async feedback, and reduced-motion support.
- Shadcn Missing Components: Find and Install Them Safely
Find components that shadcn does not include, inspect community registry code before installing it, and diagnose broken namespace or JSON responses.