useCopyToClipboard

A hook to copy text to the system clipboard using the modern Clipboard API.

Warning

The Clipboard API requires a Secure Context (HTTPS). On non-secure origins, navigator.clipboard will be undefined, and the hook will throw an error.

Important

This method must be called within a short delay after a user interaction (like a click event) to be permitted by the browser's security model.

Installation

bash

Description

This hook provides a robust way to interact with the navigator.clipboard API. It manages the state of the last copied text and handles environment checks to ensure the API is available before execution.

Return values

NameTypeDescription
copyToClipboard(text: string) => Promise<void>Async function that writes the provided string to the clipboard.
textCopiedstring | nullThe last successfully copied string. Defaults to null.

Demo

Copy to Clipboard

Source code

tsx