useCopyToClipboard
Copy text to the clipboard and show a "copied" state for a short time.
useCopyToClipboard copies a string with the Clipboard API and sets isCopied to true for a set time afterwards.
Import#
typescript
import { useCopyToClipboard } from "@reactberry/system";
import type { useCopyToClipboardProps } from "@reactberry/system";
Usage#
typescript
"use client";
import { useCopyToClipboard } from "@reactberry/system";
import { Button } from "@reactberry/system/elements";
export default function CopyButton({ value }: { value: string }) {
const { isCopied, copyToClipboard } = useCopyToClipboard({ timeout: 1500 });
return (
<Button variant="ghost" onClick={() => copyToClipboard(value)}>
{isCopied ? "Copied" : "Copy"}
</Button>
);
}
Examples#
Custom timeout#
Set timeout to change how long isCopied stays true. Here the confirmation stays for 5 seconds.
npm install @reactberry/systemAPI#
typescript
function useCopyToClipboard({ timeout }: useCopyToClipboardProps): {
isCopied: boolean;
copyToClipboard: (value: string) => void;
}
Parameters#
| Prop | Type | Default | Description |
|---|---|---|---|
options* | useCopyToClipboardProps | — | Options object. Pass |
options.timeout | number | 2000 | How long |
Returns#
| Prop | Type | Default | Description |
|---|---|---|---|
isCopied | boolean | — |
|
copyToClipboard | (value: string) => void | — | Copies |
Accessibility#
- The hook only tracks state and announces nothing. To announce a successful copy to screen readers, render the message in an
aria-liveregion.
Notes#
- The options object is required: call
useCopyToClipboard({})for the default timeout. Calling it with no argument throws. - Nothing happens for an empty string, during server rendering, or when
navigator.clipboard.writeTextis unavailable (for example on non-HTTPS pages). - A failed copy (for example, permission denied) is not caught and does not change
isCopied. - Each copy starts a new timer without clearing the previous one, so after repeated copies
isCopiedturnsfalsewhen the first timer ends.