38 lines
932 B
TypeScript
38 lines
932 B
TypeScript
|
|
import { useState, useCallback } from 'react';
|
||
|
|
|
||
|
|
/**
|
||
|
|
* Reusable hook for copy-to-clipboard with visual feedback.
|
||
|
|
*
|
||
|
|
* Returns a `copied` boolean (true for `resetDelay` ms after a successful
|
||
|
|
* copy) and a `copy` async function.
|
||
|
|
*
|
||
|
|
* @example
|
||
|
|
* ```tsx
|
||
|
|
* const { copied, copy } = useCopyToClipboard();
|
||
|
|
*
|
||
|
|
* <Button onClick={() => copy(someText)}>
|
||
|
|
* {copied ? <Check className="h-4 w-4 text-success" /> : <Copy className="h-4 w-4" />}
|
||
|
|
* {copied ? 'Copied!' : 'Copy'}
|
||
|
|
* </Button>
|
||
|
|
* ```
|
||
|
|
*/
|
||
|
|
export function useCopyToClipboard(resetDelay = 2000) {
|
||
|
|
const [copied, setCopied] = useState(false);
|
||
|
|
|
||
|
|
const copy = useCallback(
|
||
|
|
async (text: string) => {
|
||
|
|
try {
|
||
|
|
await navigator.clipboard.writeText(text);
|
||
|
|
setCopied(true);
|
||
|
|
setTimeout(() => setCopied(false), resetDelay);
|
||
|
|
return true;
|
||
|
|
} catch {
|
||
|
|
return false;
|
||
|
|
}
|
||
|
|
},
|
||
|
|
[resetDelay],
|
||
|
|
);
|
||
|
|
|
||
|
|
return { copied, copy };
|
||
|
|
}
|