ReactUseKit

useCopyToClipboard

A custom hook to copy text to the clipboard in React applications.

Installation

pnpm dlx shadcn@latest add https://reactusekit.dev/r/use-copy-to-clipboard.json

Usage

import { useCopyToClipboard } from "@/hooks/use-copy-to-clipboard";

function App() {
  const { copy, copied, error } = useCopyToClipboard();

  const handleCopy = () => {
    copy("Hello from clipboard!");
  };

  return (
    <div>
      <button onClick={handleCopy}>{copied ? "Copied!" : "Copy Text"}</button>
      {error && <p style={{ color: "red" }}>{error}</p>}
    </div>
  );
}

API

Returns

NameTypeDescription
copy(text: string) => Promise<boolean>Function to copy the given text
copiedbooleanIndicates whether the copy was successful
errorstring | nullError message if copying failed