useClipboard

A React Hook that copy text with Clipboard API or fallback to document.execCommand('copy') if it's not available.

Demo

Source
Clipboard content:

Usage

See API for more details.

Source

Click links below to view source on GitHub.

API

const clipboard = useClipboard(options)

Options

export type UseClipboardOptions<Source> = { /** * Enabled reading for clipboard, need to request permission * * @defaultValue false */ read?: boolean /** * Copy source, which is copied by default when you call the copy method directly without passing any parameters */ source?: Source /** * Milliseconds to reset state of `copied` ref * * @defaultValue 1_500 */ copiedDuration?: number }

Returns

export interface UseClipboardReturns<HasSource> { /** * Whether the Clipboard API is supported */ isSupported: boolean /** * The text in the clipboard */ text: string /** * A flag to indicate the text is copied, will be reset after `copiedDuration` */ copied: boolean /** * Copy the text to the clipboard */ copy: HasSource extends true ? (text?: string) => Promise<void> : (text: string) => Promise<void> /** * Clear the text in the clipboard */ clear(): void }