Skip to content
Thrum

Copy button

A button that puts a value on the clipboard: a command, a link, an ID. The icon turns into a tick for 2 seconds and a screen reader hears Copied. When the browser refuses the clipboard it shows a cross and says so. Place it beside the text it copies.

Install

npx shadcn@latest add https://thrumui.dev/r/copy-button.json

Adds components/ui/copy-button.tsx. Nothing else in your project changes.

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

Automatically installs icons check, copy and x from the icon set.

Props

PropTypeDefaultDescription
valuestringRequiredThe text that goes to the clipboard.
variant"outline" | "ghost" | "secondary" | "primary" | "destructive"Default "outline"The button variant.
size"sm" | "md" | "lg"Default "md"sm is 28 pixels tall, md 32, lg 40. With no children the button is a square of that size.
timeoutnumberDefault 2000How long the tick, or the cross, stays before the copy icon returns, in milliseconds.
onCopied(value: string) => void–Called with the value once it is on the clipboard.
onCopyError(error: unknown) => void–Called when the browser refuses the clipboard: no permission, or a page that is not served over HTTPS.
copiedLabelstringDefault "Copied"What a screen reader hears after a copy.
errorLabelstringDefault "Copy failed"What a screen reader hears when the copy was refused.
soundbooleanDefault truePlay the completion sound after a copy and the failure sound after a refusal, if the visitor has sound on.
childrenReactNode–A label beside the icon. Without it the button is a square named Copy.
aria-labelstringDefault "Copy"The name of a button with no children. Say what is copied: Copy install command.
disabledbooleanDefault falseThe native attribute: the button leaves the tab order and cannot be pressed.
classNamestring–Extra classes, merged last.
...propsComponentProps<"button">–Every other button attribute is passed through. An onClick that calls preventDefault stops the copy.

Motion and sound

Motion

  • The copy icon shrinks to 50% and fades out while the tick grows and fades in, over 150 ms. After 2 seconds the change runs back.
  • A refused copy shows a cross the same way.
  • The button keeps its size in every state.
  • Reduced motion: the icons swap at once.

Sound

  • Two rising tones when the value is on the clipboard.
  • Two falling tones when the browser refused the copy.

Sound is off until the visitor turns it on. Pass sound={false} to keep this component silent. How sound works

Accessibility

  • It is a native button. Its name is its label, or Copy when it has only the icon; give it an aria-label that says what is copied.
  • The result is announced through a polite live region inside the button: Copied, or Copy failed. The button's name does not change, so the result is heard once.
  • A refusal is visible as well as audible: the icon becomes a cross in the destructive colour and the border turns to it.
  • The clipboard needs a secure page (HTTPS or localhost). Elsewhere every press ends in the error state and calls onCopyError.
  • The smallest size is a 28 pixel square, above the 24 pixel minimum for pointer targets.
KeysAction
TabFocus the button.
Enter / SpaceCopy the value. Focus stays on the button.

Source

components/ui/copy-button.tsx
"use client";

import { useEffect, useId, useRef, useState, type ComponentProps } from "react";

import { cn } from "@/lib/utils";
import { play } from "@/lib/thrum-sound";
import { BUTTON_SURFACE, buttonClass, type ButtonVariant } from "@/components/ui/button";
import { CheckIcon } from "@/components/icons/check";
import { CopyIcon } from "@/components/icons/copy";
import { XIcon } from "@/components/icons/x";

export type CopyButtonState = "idle" | "copied" | "error";

export type CopyButtonProps = Omit<ComponentProps<"button">, "value"> & {
  /** The text that goes to the clipboard. */
  value: string;
  /** The button variant. */
  variant?: Exclude<ButtonVariant, "link">;
  /** `sm` is 28 pixels tall, `md` 32, `lg` 40. With no children the button is a square of that size. */
  size?: "sm" | "md" | "lg";
  /** How long the tick, or the cross, stays before the copy icon returns, in milliseconds. */
  timeout?: number;
  /** Called with the value once it is on the clipboard. */
  onCopied?: (value: string) => void;
  /** Called when the browser refuses the clipboard: no permission, or a page that is not served securely. */
  onCopyError?: (error: unknown) => void;
  /** What a screen reader hears after a copy. */
  copiedLabel?: string;
  /** What a screen reader hears when the copy was refused. */
  errorLabel?: string;
  /** Play the completion sound after a copy and the failure sound after a refusal, if the visitor has sound on. */
  sound?: boolean;
};

/** Without a label the button is a square. */
const SQUARE = { sm: "w-7 px-0", md: "w-8 px-0", lg: "w-10 px-0" } as const;

const ICONS: Record<CopyButtonState, typeof CopyIcon> = {
  idle: CopyIcon,
  copied: CheckIcon,
  error: XIcon,
};

/**
 * A button that puts `value` on the clipboard. Its icon turns into a tick for two seconds, and a live region says "Copied".
 * When the browser refuses, it shows a cross in the destructive colour and says so instead of failing silently.
 * With children it is an icon and a label; without, a square icon button named "Copy" (pass an `aria-label` to say what is copied).
 */
export function CopyButton({
  value,
  variant = "outline",
  size = "md",
  timeout = 2000,
  onCopied,
  onCopyError,
  copiedLabel = "Copied",
  errorLabel = "Copy failed",
  sound = true,
  className,
  children,
  onClick,
  "aria-label": ariaLabel,
  "aria-labelledby": ariaLabelledby,
  ...props
}: CopyButtonProps) {
  const labelId = useId();
  const [state, setState] = useState<CopyButtonState>("idle");
  const timer = useRef<ReturnType<typeof setTimeout>>(undefined);
  const mounted = useRef(false);

  useEffect(() => {
    mounted.current = true;
    return () => {
      mounted.current = false;
      clearTimeout(timer.current);
    };
  }, []);

  const copy = async () => {
    let failure: unknown = null;
    try {
      // Missing on a page that is not served securely: that is a refusal too.
      await navigator.clipboard.writeText(value);
    } catch (error) {
      failure = error ?? new Error("Clipboard unavailable");
    }
    // The clipboard answers later. A button that has left the page starts no timer.
    if (!mounted.current) return;
    setState(failure ? "error" : "copied");
    if (sound) play(failure ? "error" : "success");
    if (failure) onCopyError?.(failure);
    else onCopied?.(value);
    clearTimeout(timer.current);
    timer.current = setTimeout(() => setState("idle"), timeout);
  };

  return (
    <button
      data-slot="copy-button"
      data-surface={BUTTON_SURFACE[variant]}
      data-state={state}
      type="button"
      // The name stays the label while the live region below changes, so "Copied" is heard once, as a status.
      aria-label={ariaLabel ?? (children || ariaLabelledby ? undefined : "Copy")}
      aria-labelledby={ariaLabelledby ?? (children && !ariaLabel ? labelId : undefined)}
      className={cn(
        buttonClass({ variant, size }),
        "max-w-full gap-2",
        !children && SQUARE[size],
        state === "error" && "border-destructive",
        className,
      )}
      onClick={(event) => {
        onClick?.(event);
        if (!event.defaultPrevented) void copy();
      }}
      {...props}
    >
      <span aria-hidden="true" className={cn("grid size-4 flex-none", state === "error" && (variant === "outline" || variant === "ghost") && "text-destructive")}>
        {(Object.keys(ICONS) as CopyButtonState[]).map((icon) => {
          const Glyph = ICONS[icon];
          return (
            <Glyph
              key={icon}
              size={16}
              className={cn("col-start-1 row-start-1 transition-[opacity,scale] duration-150 ease-out motion-reduce:transition-none", icon !== state && "scale-50 opacity-0")}
            />
          );
        })}
      </span>
      {children && (
        <span id={labelId} className="min-w-0 truncate">
          {children}
        </span>
      )}
      <span role="status" aria-live="polite" className="sr-only">
        {state === "copied" ? copiedLabel : state === "error" ? errorLabel : ""}
      </span>
    </button>
  );
}

Files and dependencies

Adds
components/ui/copy-button.tsx
Packages
None
Brings along
ButtonSound engine
Icons
checkcopyx

Changelog

  1. 1.0.0 · 2026-12-03First release.

Loading index…

Keyboard shortcuts

/Ctrl KSearch components, docs and actions
?Show this list
AAppearance studio
SSound on or off
MFull or reduced motion
TTheme: auto, light, dark
GSurface: solid or frosted
BBackdrop photograph (under glass)
CCorner radius: square to round
RReplay the demo, on a component page
DDraw new data, on a component page
←→HomeEndMove the cursor in a focused chart
EscClose a dialog, or leave a chart cursor