Skip to Content
Zuri
Components

Copy button

A button that copies text and confirms it visually and to screen readers, in any Button style, with recipes for command boxes and share links.

Live preview
Theme
Preview width

Use CopyButton next to something users will paste elsewhere: a link, an install command, an account number. It says "Copied" when it worked and "Copy failed" when it didn't.

Installation

pnpm dlx shadcn@latest add https://components.abdulqadirmsingi.com/r/copy-button.json

This also installs Button, which it is built on.

Usage

import { CopyButton } from "@/components/ui/copy-button";

<CopyButton value="https://zuri.dev/r/button.json" label="Copy link" />
<CopyButton value={command} iconOnly label="Copy command" />

Styles

It accepts every Button style, so it can match the rest of your page.

Live preview
Theme
Preview width

Alternatives

Two common shapes built by placing the same CopyButton inside other elements. Nothing extra is installed.

Live preview
Theme
Preview width
npx shadcn@latest add button

Command box. A shell command with the button at its end. The $ is decorative, and long commands wrap instead of scrolling sideways.

<div className="flex items-center gap-2 rounded-xl border border-border bg-muted py-2 ps-4 pe-2">
  <span aria-hidden="true" className="select-none font-mono text-sm text-accent-ink">$</span>
  <code className="min-w-0 flex-1 break-all font-mono text-sm">{command}</code>
  <CopyButton value={command} iconOnly label="Copy command" variant="ghost" size="sm" />
</div>

Share link. A read-only field with its own label, and a button beside it.

<div className="flex items-center gap-2">
  <Input readOnly aria-label="Share link" defaultValue={url} className="flex-1" />
  <CopyButton value={url} variant="accent" label="Copy link" />
</div>

Props

CopyButton takes the same props as Button (variant, size, shape and the rest), except onClick, children and loading.

Props
PropTypeDefaultDescription
valuestring–The text to copy. Required.
labelstring"Copy"Text before copying. In icon-only mode it is the accessible name.
copiedLabelstring"Copied"Text after a successful copy.
failedLabelstring"Copy failed"Text when copying was not possible.
iconOnlybooleanfalseShow only the icon, using the label as its name.
resetAfternumber2000Milliseconds before it goes back to the first label.
onCopied(value: string) => void–Called after a successful copy.

Accessibility

  • It is a native button, so Enter and Space work.
  • The result is announced through a live region (role="status") that is always on the page, so screen readers pick it up. In icon-only mode the accessible name stays the same and only the live region changes.
  • Failure is reported, never hidden. The clipboard needs a secure context (HTTPS or localhost) and a user action.
  • Under prefers-reduced-motion, the button's press animation is off.

Tokens used

The same as Button.

Known limitations

  • It uses the asynchronous Clipboard API only. There is no fallback for old browsers or insecure pages; it reports failure instead.
  • It is a client component, because it holds the copied state.
  • Don't copy secrets such as card numbers or PINs; payment components in Zuri never put those on the clipboard.

Source

"use client";import { type ReactNode, useEffect, useRef, useState } from "react";import { Button, type ButtonProps } from "@/components/ui/button";type CopyState = "idle" | "copied" | "failed";export interface CopyButtonProps extends Omit<ButtonProps, "onClick" | "children" | "loading"> {  /** The text to put on the clipboard. */  value: string;  /** Label before copying. Also the accessible name in icon-only mode. Defaults to "Copy". */  label?: string;  copiedLabel?: string;  failedLabel?: string;  /** Show only the icon. The label becomes the accessible name. */  iconOnly?: boolean;  /** How long the "Copied" feedback stays, in milliseconds. Defaults to 2000. */  resetAfter?: number;  /** Called after a successful copy. */  onCopied?: (value: string) => void;  children?: ReactNode;}const icon = {  viewBox: "0 0 24 24",  fill: "none",  stroke: "currentColor",  strokeWidth: 2,  strokeLinecap: "round",  strokeLinejoin: "round",} as const;/** * Copies `value` to the clipboard and tells the user, visually and through a live region. * The clipboard needs a secure context (HTTPS or localhost) and a user gesture; when it is * unavailable the button reports "Copy failed" instead of pretending it worked. */export function CopyButton({  value,  label = "Copy",  copiedLabel = "Copied",  failedLabel = "Copy failed",  iconOnly = false,  resetAfter = 2000,  onCopied,  size,  variant = "outline",  ...props}: CopyButtonProps) {  const [state, setState] = useState<CopyState>("idle");  const timer = useRef<ReturnType<typeof setTimeout>>(undefined);  useEffect(() => () => clearTimeout(timer.current), []);  async function copy() {    clearTimeout(timer.current);    try {      await navigator.clipboard.writeText(value);      setState("copied");      onCopied?.(value);    } catch {      setState("failed");    }    timer.current = setTimeout(() => setState("idle"), resetAfter);  }  const text = state === "copied" ? copiedLabel : state === "failed" ? failedLabel : label;  return (    <>      <Button        variant={variant}        size={iconOnly ? (size ?? "icon") : size}        // Icon-only: the label is the name and does not change; the live region reports the result.        aria-label={iconOnly ? label : undefined}        onClick={copy}        {...props}      >        {state === "copied" ? (          <svg aria-hidden="true" {...icon}>            <path d="M5 12.5l4.5 4.5L19 7.5" />          </svg>        ) : (          <svg aria-hidden="true" {...icon}>            <rect x="9" y="9" width="11" height="11" rx="2" />            <path d="M5 15V6a2 2 0 0 1 2-2h9" />          </svg>        )}        {iconOnly ? null : text}      </Button>      {/* Always mounted so screen readers pick up the change when its text appears. */}      <span role="status" className="sr-only">        {state === "idle" ? "" : text}      </span>    </>  );}

On this page