All hooks / Browser APIs

useCopyToClipboard

177 B minified and brotliedSourceMarkdown✓ Works in all modern browsers

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]
ParameterDescription
resetMsHow long copied stays true. Default 2000.

Returns [copy, copied].

Browser support

UsesChromeEdgeFirefoxSafariChrome AndroidSafari iOS
clipboard.writeTextWidely available66+79+63+13.1+66+13.4+
  • Needs a secure page (HTTPS or localhost). copy resolves to false when the browser refuses.

First version with support, from MDN's compatibility data (web-features 3.42.0, @mdn/browser-compat-data 8.1.5).