CopyButton
Use CopyButton wherever people will want a piece of text on their clipboard: a command, a link, an API key, an ID. Blocks of Code already have one; for any other action, use Button.
Copying uses the browser’s Clipboard API, which only exists in a secure context: serve the page over HTTPS (or from localhost). Elsewhere the copy fails and onError is called.
CopyButton puts a piece of text on the clipboard. After a copy it shows a check for two seconds, then goes back to the copy icon. It is icon-only unless you give it a label.
#Demos
#Basic
Without children the button shows only its icon and is named “Copy” from the locale.
pnpm add Pika#With a label
Children become a visible label beside the icon.
#Size
Heights match Button of the same size.
#Text from a function
text can be a function; it runs on click, so it can read the latest value. onCopy gets the text once the clipboard accepted it, and onError gets the error when it did not.
Last copied: nothing yet
#Disabled
#Accessibility
CopyButton is a native button type="button", so Space and Enter copy. Icon-only, it is named by the locale’s “Copy” (or your aria-label); with a label, the label names it. After a copy its name becomes the locale’s “Copied” for copiedDuration, so a screen reader hears the result. The icons are hidden from assistive tech.
#Props
| Name | Type | Default | Description | Version |
|---|---|---|---|---|
text | string | (() => string) | required | The text to copy, or a function that returns it at click time. | Unreleased |
onCopy | (text: string) => void | undefined | Called with the copied text once the clipboard accepted it. | Unreleased |
onError | (error: unknown) => void | undefined | Called when the clipboard is missing or refuses the text. | Unreleased |
copiedDuration | number | 2000 | How long, in ms, the copied state lasts. | Unreleased |
size | small | medium | large | medium | Button size. | Unreleased |
icon | ReactNode | copy icon | Replaces the copy icon. | Unreleased |
copiedIcon | ReactNode | check icon | Replaces the check shown after a copy. | Unreleased |
children | ReactNode | undefined | A visible label; without it the button is icon-only. | Unreleased |
aria-label | string | locale “Copy” when icon-only | Names the idle button; after a copy it reads the locale’s “Copied”. | Unreleased |
disabled | boolean | false | Disables the button. | Unreleased |
CopyButton also accepts native button attributes and a ref. Restyle it through the --p-copy-button-* tokens.