Skip to content

How to copy an API key to clipboard

This example demonstrates how to copy an API key to clipboard using the useClipboard hook.

Watch the live preview.

tsx
import { useClipboard } from "./useClipboard";

const APIKeys = [
  { id: 1, name: "API Key 1", value: "1234-5678-ABCD-EFGH" },
  { id: 2, name: "API Key 2", value: "IJKL-9876-MNOP-QRST" },
  { id: 3, name: "API Key 3", value: "UVWX-5432-YZAB-CDEF" },
];

export default function App() {
  const { copiedText, copyToClipboard } = useClipboard();

  const handleCopy = async (keyValue: string, keyName: string) => {
    try {
      await copyToClipboard(keyValue);
      alert(`Copied: ${keyName}`);
    } catch (e) {
      alert("Failed to copy:");
    }
  };

  return (
    <ul>
      {APIKeys.map((key) => (
        <li key={key.id}>
          <div>
            <p>{key.name}</p>
            <p>{key.value}</p>
          </div>
          <button onClick={() => handleCopy(key.value, key.name)}>
            {copiedText === key.value ? "Copied!" : "Copy"}
          </button>
        </li>
      ))}
    </ul>
  );
}
typescript
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 };
};