How to copy to clipboard in Next.js

How to copy a string to the clipboard in Next.js

date

Clipboard API

Define a function

const copyToClipboard = async (text: string) => {
  try {
    navigator.clipboard.writeText(text);
  } catch (err) {
    console.error(err);
  }
};

Call the function

  <button onClick={() => copyToClipboard("Copy")}>Copy</button>

Change the text when copied

A common use case is to change the text after copying to let the user know that the text has been copied.

const [isCopied, setIsCopied] = useState(false);

const copyToClipboard = async (text: string) => {
  try {
    await navigator.clipboard.writeText(text);
    setIsCopied(true);
    setTimeout(() => {
      setIsCopied(false);
    }, 1000);
  } catch (err) {
    console.error(err);
  }
};

return (
  <button onClick={() => copyToClipboard("Copy")}>
    {isCopied ? "Copied!" : "Copy"}
  </button>
);
Share