Hooks

useCopy

A hook that copies text to the clipboard with optional toast and success/error states. Also includes a built-in, customizable CopyButton component.

Installation

pnpm dlx shadcn@latest add https://rafay.sh/r/use-copy.json

Usage

1import { useCopy } from "@/hooks/use-confirm.tsx";
1const { CopyButton, copied, copy } = useCopy({ 2 delay: 2000, 3 showToast: true, 4}); 5 6// Button component provided in the hook: 7<CopyButton text="textToCopy"> 8 {copied ? "Copied" : "Copy"} 9</CopyButton> 10 11// Or your own button component: 12<button 13 type="button" 14 className="h-10 px-4 rounded-md bg-neutral-800 text-white hover:scale-105 duration-200 transition-all" 15 onClick={() => copy("textToCopy")} 16> 17 {copied ? "Copied" : "Copy"} 18</button>

useCopy Props

PropTypeDefaultDescription
delaynumber1500Duration (in ms) for how long the copied or error state should remain before resetting.
showToastbooleanfalseWhether to show a toast notification using sonner after copying or on error.
successMessagestringundefinedCustom success toast message shown when text is successfully copied.
errorMessagestringundefinedCustom error toast message shown when copying fails.

<CopyButton /> Props

PropTypeDefaultDescription
textstringundefinedThe text value that will be copied to clipboard when clicked.
childrenReact.ReactNodeundefinedThe button label or any node rendered inside the button.
variantButtonVariants["variant"]undefinedButton variant inherited from shadcn buttonVariants.
sizeButtonVariants["size"]undefinedButton size inherited from shadcn buttonVariants.
classNamestring""Custom class names for styling the CopyButton.