useClipboard
useClipboard(options?) returns copy(text), which writes text to the clipboard, status, the outcome of the latest copy, text, the text that outcome is for, and reset(). Use it for copy buttons, such as on a code block, a link or a message.
On this page
const { copy, status } = useClipboard();
<Button.Root onClick={() => copy(command)}>Copy command</Button.Root>
{status === 'copied' ? <Text.Root>Copied</Text.Root> : null}
pnpm add @tounsoo/todaecopy calls navigator.clipboard.writeText and resolves to true when the text was copied and false when it was not. Once the latest copy settles, status is 'copied' or 'failed' and text is the text that copy was for. Both go back to 'idle' and null once resetAfter passes, 2000 milliseconds by default, or when you call reset(). Pass resetAfter: false to keep them until the next copy or reset(). While a copy is pending, the previous outcome stays. When copies overlap, only the latest one sets status and is announced.
There is no execCommand fallback. Where the Clipboard API is missing or refused, such as on a page that is not a secure context, the copy fails.
Accessible composition
Todae handles: Announcing the latest copy's outcome through useAnnouncer: the copied string politely after a copy, and the copyFailed string assertively when a copy fails. Both come from StringsProvider unless you pass copiedMessage or failedMessage. A copy that settles after the component unmounts is still announced.
You supply: A button with a name that says what it copies, such as "Copy command" rather than "Copy" when a page has several. A visible result next to it for sighted users, from status. Messages in the reader's language, through StringsProvider or the options.
Watch for: A visible result in a live region of its own, such as an Alert, is read twice; pass an empty copiedMessage or failedMessage to read nothing. Changing the button's own text to "Copied" can be read by a screen reader as well as the announcement.
When to use
When: A control that copies text the product already has, such as a command, a link or a message.
When not: Copying rich content such as images or HTML → navigator.clipboard.write in your own code. Text the reader selects and copies themselves → the browser does that already.
Props
| Name | Type | Description |
|---|---|---|
resetAfter | number | false | Milliseconds before status returns to "idle". false keeps it until the next copy or reset(). Default: 2000 |
copiedMessage | string | Read to screen readers after a copy. Default is the copied string from StringsProvider. An empty string reads nothing. |
failedMessage | string | Read to screen readers, assertively, when a copy fails. Default is the copyFailed string from StringsProvider. An empty string reads nothing. |