useCopyToClipboard()
This React hook provides a copy
method to save a string in the clipboard and the copied value (default: null
).
If anything doesn't work, it prints a warning in the console and the value will be null
.
The Hook
1import { useState } from 'react'23type CopiedValue = string | null4type CopyFn = (text: string) => Promise<boolean> // Return success56function useCopyToClipboard(): [CopiedValue, CopyFn] {7 const [copiedText, setCopiedText] = useState<CopiedValue>(null)89 const copy: CopyFn = async text => {10 if (!navigator?.clipboard) {11 console.warn('Clipboard not supported')12 return false13 }1415 // Try to save to clipboard then save it in the state if worked16 try {17 await navigator.clipboard.writeText(text)18 setCopiedText(text)19 return true20 } catch (error) {21 console.warn('Copy failed', error)22 setCopiedText(null)23 return false24 }25 }2627 return [copiedText, copy]28}2930export default useCopyToClipboard
Usage
1import { useCopyToClipboard } from 'usehooks-ts'23export default function Component() {4 const [value, copy] = useCopyToClipboard()5 return (6 <>7 <h1>Click to copy:</h1>8 <div style={{ display: 'flex' }}>9 <button onClick={() => copy('A')}>A</button>10 <button onClick={() => copy('B')}>B</button>11 <button onClick={() => copy('C')}>C</button>12 </div>13 <p>Copied value: {value ?? 'Nothing is copied yet!'}</p>14 </>15 )16}
See a way to make this page better?
Edit there »