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
Name | Type | Description |
---|---|---|
copy | (text: string) => Promise<boolean> | Function to copy the given text |
copied | boolean | Indicates whether the copy was successful |
error | string | null | Error message if copying failed |