Shadcn Clipboard
A copy to clipboard component for links, API keys, codes and commands. Use it as a labeled read-only input with a copy button, or as a standalone button. The indicator swaps to a check after copying and back after a timeout, failures show an error state, and every copy is announced to screen readers.
Installation
npx shadcn@latest add @shadcnuikit/clipboard1
This adds components/ui/clipboard.tsx, the button, input-group and label components it depends on, and a demo file. Set up the registry once as described in Shadcn CLI. Clipboard is free and installs without an API key.
Manual installation
Install the dependencies and the button, input-group and label components:
npm install @ui-sdk/core@beta @ui-sdk/react@beta lucide-react
npx shadcn@latest add button input-group label
Copy the source into components/ui/clipboard.tsx:
"use client";
import * as React from "react";import { announce, createChange, definePrimitive, prepareAnnouncements, type ChangeDetails,} from "@ui-sdk/core";import { createParts } from "@ui-sdk/react/primitive";import { CheckIcon, CopyIcon, TriangleAlertIcon } from "lucide-react";
import { Button } from "@/components/ui/button";import { InputGroup, InputGroupButton, InputGroupInput } from "@/components/ui/input-group";import { Label } from "@/components/ui/label";import { cn } from "@/lib/utils";
// "set-value" isn't in the shared vocabulary.type ClipboardReason = "set-value";
type ClipboardStatus = { copied: boolean; error: Error | null; value: string };
type ClipboardOptions = { value?: string; defaultValue?: string; onValueChange?: (value: string, details: ChangeDetails<ClipboardReason>) => void; onCopy?: (value: string) => void; onStatusChange?: (status: ClipboardStatus) => void; timeout?: number; html?: string; disabled?: boolean; write?: (value: string, html?: string) => Promise<void>;};
type ClipboardState = { value: string; copied: boolean; error: string | null; disabled: boolean;};
async function writeToClipboard(value: string, html?: string) { const clipboard = globalThis.navigator?.clipboard; if (!clipboard) throw new Error("Clipboard is unavailable in this browser"); if (html && typeof ClipboardItem !== "undefined" && clipboard.write) { await clipboard.write([ new ClipboardItem({ "text/plain": new Blob([value], { type: "text/plain" }), "text/html": new Blob([html], { type: "text/html" }), }), ]); return; } await clipboard.writeText(value);}
const clipboard = definePrimitive({ name: "clipboard", options: { value: "string", defaultValue: "string", onValueChange: "callback", onCopy: "callback", onStatusChange: "callback", timeout: "number", html: "string", disabled: "boolean", write: "action", }, controlled: ["value"], state: (options: ClipboardOptions): ClipboardState => ({ value: options.value ?? options.defaultValue ?? "", copied: false, error: null, disabled: options.disabled ?? false, }), sync: (options) => ({ ...(options.value === undefined ? {} : { value: options.value }), disabled: options.disabled ?? false, }), api: (context) => { const change = createChange(context); let timer: ReturnType<typeof setTimeout> | undefined; let attempt = 0; let value = context.store.get().value;
const report = (copied: boolean, error: Error | null) => { context.options().onStatusChange?.({ copied, error, value: context.store.get().value }); };
const reset = () => { clearTimeout(timer); timer = undefined; const { copied, error } = context.store.get(); if (!copied && !error) return; context.store.set({ copied: false, error: null }); report(false, null); };
const later = () => { clearTimeout(timer); const timeout = context.options().timeout ?? 2000; if (timeout > 0) timer = setTimeout(reset, timeout); };
context.onDestroy( context.store.subscribe(() => { const next = context.store.get().value; if (next === value) return; value = next; reset(); }), ); context.onDestroy(() => clearTimeout(timer));
return { reset, setValue(next: string, event?: Event) { return change("value", next, { reason: "set-value", event }); }, async copy() { const state = context.store.get(); if (state.disabled) return false; const { html, write = writeToClipboard, onCopy } = context.options(); const current = ++attempt; try { await write(state.value, html); if (current !== attempt) return true; context.store.set({ copied: true, error: null }); announce("Copied to clipboard"); onCopy?.(state.value); report(true, null); later(); return true; } catch (cause) { if (current !== attempt) return false; const error = cause instanceof Error ? cause : new Error("Copy failed"); context.store.set({ copied: false, error: error.message }); announce(`Copy failed: ${error.message}`, { priority: "assertive" }); report(false, error); later(); return false; } }, }; }, slots: (slot) => ({ root: slot<{}, { copied: boolean; error: string | null; value: string }>({ role: "group", state: (state) => ({ copied: state.copied, error: state.error, value: state.value }), attrs: (state) => ({ "data-copied": state.copied ? "" : undefined, "data-error": state.error ? "" : undefined, "data-disabled": state.disabled ? "" : undefined, }), bind: (el) => prepareAnnouncements(el.ownerDocument), }), label: slot({ attrs: (state, part) => ({ id: `${part.id}-label`, for: `${part.id}-input`, "data-disabled": state.disabled ? "" : undefined, }), bind: (el) => { const root = el.closest<HTMLElement>('[data-slot="clipboard"]'); if (!root || root.hasAttribute("aria-label")) return; root.setAttribute("aria-labelledby", el.id); return () => root.removeAttribute("aria-labelledby"); }, }), control: slot({ attrs: (state) => ({ "data-copied": state.copied ? "" : undefined, "data-error": state.error ? "" : undefined, "data-disabled": state.disabled ? "" : undefined, }), }), input: slot({ attrs: (state, part) => ({ id: `${part.id}-input`, value: state.value, readonly: "", disabled: state.disabled ? "" : undefined, "aria-invalid": state.error ? "true" : undefined, "data-copied": state.copied ? "" : undefined, }), on: { focus: (event) => (event.target as HTMLInputElement).select(), }, }), trigger: slot<{}, { copied: boolean; error: string | null }>({ state: (state) => ({ copied: state.copied, error: state.error }), attrs: (state) => ({ type: "button", "aria-disabled": state.disabled ? "true" : undefined, "data-copied": state.copied ? "" : undefined, "data-error": state.error ? "" : undefined, }), press: ({ api }) => { void api.copy(); }, }), indicator: slot<{}, { copied: boolean; error: string | null }>({ state: (state) => ({ copied: state.copied, error: state.error }), attrs: (state) => ({ "data-copied": state.copied ? "" : undefined, "data-error": state.error ? "" : undefined, }), }), "value-text": slot<{}, { value: string }>({ state: (state) => ({ value: state.value }), }), }), agent: { actions: ["copy", "setValue"] },});
const Parts = createParts(clipboard, { root: "div", label: "label", control: "div", input: "input", trigger: "button", indicator: "span", "value-text": "span",});
type PartClassName<T> = Omit< React.ComponentProps<T extends React.ElementType ? T : never>, "className"> & { className?: string;};
type ButtonStyleProps = Pick<React.ComponentProps<typeof Button>, "variant" | "size">;
function Clipboard({ className, ...props }: PartClassName<typeof Parts.Root>) { return ( <Parts.Root className={cn("flex w-full flex-col gap-2", className)} {...props} /> );}
function ClipboardLabel({ className, ...props }: PartClassName<typeof Parts.Label>) { return ( <Parts.Label render={<Label />} className={cn("data-disabled:opacity-50", className)} {...props} /> );}
function ClipboardControl({ className, ...props }: PartClassName<typeof Parts.Control>) { return ( <Parts.Control render={<InputGroup />} className={cn( "has-[[data-slot=clipboard-input]:focus-visible]:border-ring has-[[data-slot=clipboard-input]:focus-visible]:ring-ring/50 has-[[data-slot=clipboard-input]:focus-visible]:ring-3", "data-error:border-destructive data-error:ring-destructive/20 dark:data-error:ring-destructive/40 data-error:ring-3", className, )} {...props} /> );}
function ClipboardInput({ className, ...props }: PartClassName<typeof Parts.Input>) { return ( <Parts.Input render={<InputGroupInput />} className={cn("text-muted-foreground truncate font-mono text-xs", className)} {...props} /> );}
function ClipboardTrigger({ className, variant = "outline", size = "icon", ...props}: PartClassName<typeof Parts.Trigger> & ButtonStyleProps) { return ( <Parts.Trigger render={<Button variant={variant} size={size} />} className={cn("aria-disabled:pointer-events-none aria-disabled:opacity-50", className)} {...props} /> );}
function ClipboardInputTrigger({ className, size = "icon-xs", ...props}: PartClassName<typeof Parts.Trigger> & { size?: React.ComponentProps<typeof InputGroupButton>["size"];}) { return ( <Parts.Trigger render={<InputGroupButton size={size} />} className={cn("aria-disabled:pointer-events-none aria-disabled:opacity-50", className)} {...props} /> );}
function ClipboardIndicator({ className, children, copied, error, ...props}: Omit<PartClassName<typeof Parts.Indicator>, "children"> & { children?: React.ReactNode; copied?: React.ReactNode; error?: React.ReactNode;}) { return ( <Parts.Indicator className={cn( "inline-flex shrink-0 items-center gap-1.5 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4", "data-copied:animate-in data-copied:zoom-in-75 data-error:animate-in data-error:zoom-in-75", className, )} {...props} > {(state) => { if (state.error) return error ?? <TriangleAlertIcon aria-hidden="true" />; if (state.copied) return copied ?? <CheckIcon aria-hidden="true" />; return children ?? <CopyIcon aria-hidden="true" />; }} </Parts.Indicator> );}
function ClipboardValueText({ className, ...props }: PartClassName<typeof Parts.ValueText>) { return ( <Parts.ValueText className={cn("truncate", className)} {...props}> {({ value }) => value} </Parts.ValueText> );}
export { Clipboard, ClipboardControl, ClipboardIndicator, ClipboardInput, ClipboardInputTrigger, ClipboardLabel, ClipboardTrigger, ClipboardValueText, clipboard,};export type { ClipboardOptions, ClipboardReason, ClipboardStatus };
Usage
import {
Clipboard,
ClipboardControl,
ClipboardIndicator,
ClipboardInput,
ClipboardInputTrigger,
ClipboardLabel,
} from "@/components/ui/clipboard";
import { InputGroupAddon } from "@/components/ui/input-group";
<Clipboard defaultValue="https://example.com/invite/7f3a">
<ClipboardLabel>Invite link</ClipboardLabel>
<ClipboardControl>
<ClipboardInput />
<InputGroupAddon align="inline-end">
<ClipboardInputTrigger aria-label="Copy invite link">
<ClipboardIndicator />
</ClipboardInputTrigger>
</InputGroupAddon>
</ClipboardControl>
</Clipboard>
ClipboardControl is an InputGroup, so the trigger sits inside an InputGroupAddon. The input is read-only and selects its text on focus.
Button only
<Clipboard defaultValue="ORDER-48213" aria-label="Order number" className="w-auto">
<ClipboardTrigger aria-label="Copy order number">
<ClipboardIndicator />
</ClipboardTrigger>
</Clipboard>
Without a ClipboardLabel, name the group with aria-label. The root is w-full, so add w-auto when it sits inline.
Controlled
const [link, setLink] = React.useState("https://example.com/a");
<Clipboard value={link}>
...
</Clipboard>;
Pass value when the text comes from your own state, like a link that changes with a setting. Changing the value resets the copied state, so the check never shows for text that wasn't copied. onCopy runs after each successful copy with the copied text.
Examples
Button
ClipboardTrigger renders a shadcn/ui Button. Its children can be a function that receives copied and error, to swap the text.
Value Text
ClipboardValueText shows the value as plain text, without an input.
Indicator
ClipboardIndicator shows its children before copying, copied after and error on failure. All three default to Lucide icons.
Timeout
timeout sets how long the copied state lasts, in milliseconds. The default is 2000, and 0 keeps it until the value changes.
Rich Text
html copies a rich version next to the plain value. Apps that accept rich text, like docs and email, paste the HTML.
Error
When the copy fails, the root, control and trigger get data-error and the input aria-invalid. Here write always rejects to show the state.
Disabled
More layouts built with Clipboard, such as API keys, install commands and share links, are on the Clipboard components page.
API Reference
Clipboard
The root, with role="group". Holds the value and connects every part inside it.
| Prop | Type | Default | Description |
|---|---|---|---|
value | string | The text to copy. Pass it to control the value. | |
defaultValue | string | "" | The text at first, when uncontrolled. |
onValueChange | (value, details) => void | Runs when the primitive's setValue changes the value, for example from an agent. details.reason is "set-value". | |
onCopy | (value) => void | Runs after a successful copy, with the copied text. | |
onStatusChange | (status) => void | Runs when the copied or error state changes. status is { copied, error, value }. | |
timeout | number | 2000 | How long the copied or error state lasts, in milliseconds. 0 keeps it. |
html | string | A rich text version to copy next to the plain text, as text/html. | |
disabled | boolean | false | Disables copying and the input. |
write | (value, html?) => Promise<void> | navigator.clipboard | Replaces how the text is written, for tests or native apps. A rejection sets the error state. |
className | string | Classes for the root. |
The root has data-copied, data-error and data-disabled attributes for styling.
ClipboardLabel
A shadcn/ui Label for the input. It names the group too, unless the root has an aria-label.
| Prop | Type | Default | Description |
|---|---|---|---|
className | string | Classes for the label. |
ClipboardControl
An InputGroup around the input and its trigger. Shows a destructive ring on error.
| Prop | Type | Default | Description |
|---|---|---|---|
className | string | Classes for the group. |
ClipboardInput
A read-only InputGroupInput that shows the value in a monospace font and selects it on focus.
| Prop | Type | Default | Description |
|---|---|---|---|
className | string | Classes for the input. |
ClipboardTrigger
A standalone copy button, rendered as a shadcn/ui Button.
| Prop | Type | Default | Description |
|---|---|---|---|
variant | Button variant | "outline" | The button style. |
size | Button size | "icon" | The button size. Use "default" or "sm" when it has text. |
children | ReactNode, ({ copied, error }) => ReactNode | The content. A function swaps it by state. | |
className | string | Classes for the button. |
ClipboardInputTrigger
The copy button inside a ClipboardControl, rendered as an InputGroupButton.
| Prop | Type | Default | Description |
|---|---|---|---|
size | InputGroupButton size | "icon-xs" | The button size. |
children | ReactNode, ({ copied, error }) => ReactNode | The content, usually a ClipboardIndicator. | |
className | string | Classes for the button. |
ClipboardIndicator
The icon that follows the copy state.
| Prop | Type | Default | Description |
|---|---|---|---|
children | ReactNode | CopyIcon | Shown before copying. |
copied | ReactNode | CheckIcon | Shown after a successful copy. |
error | ReactNode | TriangleAlertIcon | Shown after a failed copy. |
className | string | Classes for the indicator. |
ClipboardValueText
The value as text, truncated when it doesn't fit.
| Prop | Type | Default | Description |
|---|---|---|---|
className | string | Classes for the text. |
Accessibility
- The root is a
groupnamed byClipboardLabelor by its ownaria-label. - The label is connected to the input with
for, and the input is read-only, so screen readers read the value and users can still select it by hand. - A successful copy announces "Copied to clipboard". A failure announces "Copy failed" with the reason, assertively, and sets
aria-invalidon the input. - Icon only triggers need an
aria-label, such as "Copy invite link". The indicator icons arearia-hidden. - A disabled clipboard sets
aria-disabledon the trigger anddisabledon the input.
For AI Agents
When to use
- Anything users copy and paste elsewhere: invite and share links, API keys, tokens, coupon codes, order numbers, install commands.
- A copy button next to a value in a table, card or code block.
When not to use
- An editable field. The input is read-only. Use an Input instead.
- Long code samples with syntax highlighting. Use a code block with its own copy button.
- Hiding secrets. Clipboard shows the value as is, so mask it yourself if it should not be visible.
Agent notes
- Import from
@/components/ui/clipboard. The exports areClipboard,ClipboardLabel,ClipboardControl,ClipboardInput,ClipboardTrigger,ClipboardInputTrigger,ClipboardIndicator,ClipboardValueText, theclipboardprimitive and theClipboardOptions,ClipboardReasonandClipboardStatustypes. - Put
ClipboardInputTriggerinsideInputGroupAddonfrom@/components/ui/input-group. UseClipboardTriggeroutside an input. - Don't call
navigator.clipboardyourself or keep acopiedstate. Read it from the trigger's function children ordata-copied. - Pass a function to
writeoronCopyonly from a client component, with"use client". - The Clipboard API needs a secure context (HTTPS or localhost). On plain HTTP the copy fails and shows the error state.
Resources
- Markdown: /docs/components/clipboard.md
- Variants: Clipboard components, 13 free examples
- Install:
npx shadcn@latest add @shadcnuikit/clipboard1 - MCP: call
get_item_codewithclipboard1from the MCP Server - Full index for agents: llms.txt