useClipboard
Copy text with the Clipboard API, with a copied flag that resets after a delay and an error when it fails.
Source@monoline/react 0.4.0Markdown for AI toolsstable
- No DOM output. Pair the copied state with a visible or aria-live status message in the UI.
- A failed copy returns false and sets error; it never throws.
Import
import '@monoline/css';
import {useClipboard} from '@monoline/react';
Not installed yet? Pick a route.
Copies the source and its styles into your project.
npx monoline add use-clipboard
Usage
import {Button, useClipboard} from '@monoline/react';
function ClipboardDemo() {
const {copied, error, copy} = useClipboard();
return (
<div>
<Button variant="line" onClick={() => copy('npm install @monoline/react')}>
{copied ? 'Copied' : 'Copy install command'}
</Button>
{error && <p role="status">Copy failed. Select the text and copy it yourself.</p>}
</div>
);
}
<ClipboardDemo />
Examples
Props
UseClipboardOptions
| Prop | Type | Default | Description |
|---|---|---|---|
timeout | number | 2000 | How long `copied` stays true, in milliseconds. Default 2000. |
UseClipboardReturn
| Prop | Type | Default | Description |
|---|---|---|---|
copied required | boolean | – | True for `timeout` ms after a successful copy. |
error required | Error | null | – | The last failure, cleared by the next copy. |
copy required | (value: string) => Promise<boolean> | – | Copies text. Resolves `true` on success, `false` on failure (never throws). |
Behaviour
- No DOM output. Pair the copied state with a visible or aria-live status message in the UI.
- A failed copy returns false and sets error; it never throws.