Skip to content

useCopyToClipboard

Copies text to the clipboard and tracks whether it worked.

Installation

  1. Add the registryOnce per project
  2. Add use-copy-to-clipboard

Usage

copy writes the text to the clipboard and resolves to whether it succeeded. After a copy, status is copied or failed for two seconds, or for resetAfter milliseconds, so a control can show the result. Otherwise it's idle. reset sets it back to idle early. This is the hook behind Copy Button, and other components with a copy button use it too.

When the Clipboard API is unavailable or rejects the write, as it can over plain HTTP or in some embedded browsers, the hook falls back to copying from a hidden text area. It then restores the previous selection and focus.

Examples

Text that loads first

When the text isn't ready yet, pass copy a promise of it, such as from a fetch. Safari only lets a page write to the clipboard during the click that requested it, so the hook passes the promise to the clipboard immediately. The clipboard receives the text once the promise resolves.

API

useCopyToClipboard

useCopyToClipboard(options?) takes these options.

It returns:

The file also exports CopyStatus, the type of status.