CopyButton
Copy a value to the clipboard and show a short copied state.
Anatomy#
Usage#
Use CopyButton to copy a string or ClipboardItem to the clipboard from a single control. It writes
through navigator.clipboard and falls back to document.execCommand('copy') when the Clipboard API
is missing or the write fails. After a copy it holds a copied or failed state for resetDelay,
then returns to idle.
Value#
value accepts a string, a ClipboardItem, a ClipboardItem[], a promise of either, or a function
that returns one. A function runs on every click, and a promise is awaited first. If either fails,
the copy fails and onCopyError receives the error. The execCommand fallback copies text only.
With text and icons#
Pass children to render a labeled button. Without children, CopyButton renders a square icon-only
button at the matching icon size. iconPosition places the icon before (leading, default) or after
(trailing) the label. Children can also be a function that receives the copy state, including
isCopied, isError, and status.
Accessible name#
The button’s aria-label is Copy to clipboard, and Copied to clipboard while copied. Override
the wording through the provider messages, or set aria-label to name what is copied. After a failed
copy the button sets aria-invalid until resetDelay elapses.
Variant, tone, and size#
variant (solid, soft, outline, ghost), tone, and size work as on
Button, but CopyButton defaults to the ghost variant and neutral tone.
Inside a ButtonGroup, it inherits the group’s size, tone, and
variant (except link).
Feedback duration and icons#
resetDelay sets how long the copied or failed state holds, in milliseconds; it defaults to 2000. Set icon for the idle glyph and copiedIcon for the copied glyph. Pass icon={false} to hide
the icon. Use onCopySuccess, onCopyError, and onStatusChange to react to the result.
Headless hook: createCopy#
createCopy from moraine/utils runs the same copy logic without a button. It
returns copy and reset, plus the isCopied, isError, status, error, and isSupported
accessors.
Examples#
Copy a command from a read-only field#
Pair a read-only Input with an icon-only CopyButton so the user can read and copy the command.
Swap icons and hold the copied state longer#
Set icon and copiedIcon for the two states, and raise resetDelay to keep the confirmation
visible.
Change the label while copied#
Pass a function child to read state.isCopied and show different label text after a copy. Set
iconPosition="trailing" to move the icon after the label.
API Reference#
Attributes#
data-copieddata-disabledProps#
Props for the CopyButton component. Renders a <button> element by default.