View as Markdown

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:

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.

sk_live_4eC39HqLyjWDarjtT1zdp7dc

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.

PropTypeDefaultDescription
valuestringThe text to copy. Pass it to control the value.
defaultValuestring""The text at first, when uncontrolled.
onValueChange(value, details) => voidRuns when the primitive's setValue changes the value, for example from an agent. details.reason is "set-value".
onCopy(value) => voidRuns after a successful copy, with the copied text.
onStatusChange(status) => voidRuns when the copied or error state changes. status is { copied, error, value }.
timeoutnumber2000How long the copied or error state lasts, in milliseconds. 0 keeps it.
htmlstringA rich text version to copy next to the plain text, as text/html.
disabledbooleanfalseDisables copying and the input.
write(value, html?) => Promise<void>navigator.clipboardReplaces how the text is written, for tests or native apps. A rejection sets the error state.
classNamestringClasses 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.

PropTypeDefaultDescription
classNamestringClasses for the label.

ClipboardControl

An InputGroup around the input and its trigger. Shows a destructive ring on error.

PropTypeDefaultDescription
classNamestringClasses for the group.

ClipboardInput

A read-only InputGroupInput that shows the value in a monospace font and selects it on focus.

PropTypeDefaultDescription
classNamestringClasses for the input.

ClipboardTrigger

A standalone copy button, rendered as a shadcn/ui Button.

PropTypeDefaultDescription
variantButton variant"outline"The button style.
sizeButton size"icon"The button size. Use "default" or "sm" when it has text.
childrenReactNode, ({ copied, error }) => ReactNodeThe content. A function swaps it by state.
classNamestringClasses for the button.

ClipboardInputTrigger

The copy button inside a ClipboardControl, rendered as an InputGroupButton.

PropTypeDefaultDescription
sizeInputGroupButton size"icon-xs"The button size.
childrenReactNode, ({ copied, error }) => ReactNodeThe content, usually a ClipboardIndicator.
classNamestringClasses for the button.

ClipboardIndicator

The icon that follows the copy state.

PropTypeDefaultDescription
childrenReactNodeCopyIconShown before copying.
copiedReactNodeCheckIconShown after a successful copy.
errorReactNodeTriangleAlertIconShown after a failed copy.
classNamestringClasses for the indicator.

ClipboardValueText

The value as text, truncated when it doesn't fit.

PropTypeDefaultDescription
classNamestringClasses for the text.

Accessibility

  • The root is a group named by ClipboardLabel or by its own aria-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-invalid on the input.
  • Icon only triggers need an aria-label, such as "Copy invite link". The indicator icons are aria-hidden.
  • A disabled clipboard sets aria-disabled on the trigger and disabled on 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 are Clipboard, ClipboardLabel, ClipboardControl, ClipboardInput, ClipboardTrigger, ClipboardInputTrigger, ClipboardIndicator, ClipboardValueText, the clipboard primitive and the ClipboardOptions, ClipboardReason and ClipboardStatus types.
  • Put ClipboardInputTrigger inside InputGroupAddon from @/components/ui/input-group. Use ClipboardTrigger outside an input.
  • Don't call navigator.clipboard yourself or keep a copied state. Read it from the trigger's function children or data-copied.
  • Pass a function to write or onCopy only 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