Skip to content

useClipboard

React hook to copy to the clipboard.

Add the hook via the CLI:

bash
npx @novajslabs/cli add useClipboard
bash
npx @novajslabs/cli add useClipboard
bash
pnpm dlx @novajslabs/cli add useClipboard

Or copy and paste the code into your project:

ts
import { useState } from "react";

export const useClipboard = () => {
  const [copiedText, setCopiedText] = useState<string | null>("");

  const copyToClipboard = async (value: string) => {
    try {
      if (navigator?.clipboard?.writeText) {
        await navigator.clipboard.writeText(value);
        setCopiedText(value);
      } else {
        throw new Error("Clipboard not supported");
      }
    } catch (e) {
      setCopiedText(null);
      throw new Error(e instanceof Error ? e.message : "Unknown error");
    }
  };

  return { copiedText, copyToClipboard };
};
js
import { useState } from "react";

export const useClipboard = () => {
  const [copiedText, setCopiedText] = useState("");

  const copyToClipboard = async (value) => {
    try {
      if (navigator?.clipboard?.writeText) {
        await navigator.clipboard.writeText(value);
        setCopiedText(value);
      } else {
        throw new Error("Clipboard not supported");
      }
    } catch (e) {
      setCopiedText(null);
      throw new Error(e instanceof Error ? e.message : "Unknown error");
    }
  };

  return { copiedText, copyToClipboard };
};

Requirements

React 16.8 or higher

Return values

copiedText

Type: string | null

The text currently copied to the clipboard. If null, it means that the copyToClipboard function encountered an error.

copyToClipboard

Type: (value: string) => Promise<void>

Copy a text to the clipboard.

Examples of common use cases