All hooks / Browser APIs
useCopyToClipboard
Copies text to the clipboard and reports copied for a short time, for a "Copied!" label.
copy resolves to true on success and false when the browser refuses (no permission, insecure context, or no Clipboard API). Copying again restarts the timer. The timer is cleared on unmount.
Import
import { useCopyToClipboard } from '@vincent.ri/react-tils'
// or only this hook
import { useCopyToClipboard } from '@vincent.ri/react-tils/useCopyToClipboard'Usage
const [copy, copied] = useCopyToClipboard()
return <button onClick={() => copy(apiKey)}>{copied ? 'Copied!' : 'Copy'}</button>Live demo
Copies a short text.
When to use it
A "Copy" button for a code snippet, link, or API key.
When not to
You need to copy rich content (HTML, images); call navigator.clipboard.write() with a ClipboardItem. Call copy from a user action (click, keypress); browsers block clipboard writes otherwise.
API
function useCopyToClipboard(resetMs?: number): [(text: string) => Promise<boolean>, boolean]| Parameter | Description |
|---|---|
resetMs | How long copied stays true. Default 2000. |
Returns [copy, copied].
Browser support
| Uses | Chrome | Edge | Firefox | Safari | Chrome Android | Safari iOS |
|---|---|---|---|---|---|---|
| clipboard.writeTextWidely available | 66+ | 79+ | 63+ | 13.1+ | 66+ | 13.4+ |
- Needs a secure page (HTTPS or localhost).
copyresolves tofalsewhen the browser refuses.
First version with support, from MDN's compatibility data (web-features 3.42.0, @mdn/browser-compat-data 8.1.5).