Skip to main content

useCopyToClipboard

The useCopyToClipboard hook provides a simple interface to copy text to the user's clipboard, with success feedback and robust error handling. It's ideal for share buttons, codes, links, and any content that users might want to copy.

Import

import { useCopyToClipboard } from 'buildgrid-ui'

Basic Usage

import { useCopyToClipboard } from 'buildgrid-ui'

function CopyButton() {
const [copiedText, copy] = useCopyToClipboard()

const handleCopy = async () => {
const success = await copy('Text copied!')
if (success) {
console.log('Text copied successfully!')
}
}

return (
<div className="space-y-2">
<button
onClick={handleCopy}
className="px-4 py-2 bg-blue-500 text-white rounded hover:bg-blue-600"
>
Copy Text
</button>

{copiedText && (
<p className="text-sm text-green-600">
✓ Copied: {copiedText}
</p>
)}
</div>
)
}

API Reference

useCopyToClipboard

function useCopyToClipboard(): [CopiedValue, CopyFn]

type CopiedValue = string | null
type CopyFn = (text: string) => Promise<boolean>

Return Value

IndexTypeDescription
[0]string | nullLast successfully copied text, or null if none.
[1](text: string) => Promise<boolean>Function to copy text. Returns true if successful.