px-react-copy-to-clipboard-hook
v1.0.2
Published
A small React hook for copying text to the clipboard with status and error handling.
Maintainers
Readme
px-react-copy-to-clipboard-hook
A small React hook for copying text to the clipboard with status and error handling.
Install
npm install px-react-copy-to-clipboard-hookyarn add px-react-copy-to-clipboard-hookUsage
import { useCopyToClipboard } from "px-react-copy-to-clipboard-hook";
export function Example() {
const { isCopied, error, handleCopy } = useCopyToClipboard();
const onCopy = async () => {
await handleCopy("Hello from the clipboard hook!");
};
return (
<div>
<button type="button" onClick={onCopy}>
Copy text
</button>
{isCopied && <p>Copied!</p>}
{error && <p>Failed to copy.</p>}
</div>
);
}API
useCopyToClipboard()
Returns the following values:
isCopied:booleanindicating whether the last copy succeeded.error:Error | nullfor the last copy failure.handleCopy(text: string): Promise<void>triggers the clipboard write.setIsCopied(isCopied: boolean): voidallows manual reset of the copied state.
Notes
navigator.clipboardrequires a secure context (HTTPS or localhost).- This hook triggers alert messages on success and failure; remove or replace those in
src/useCopyToClipboard.tsif you prefer custom UI.
