React hook for copying text to clipboard
1import { useState } from 'react';
2
3function useCopyToClipboard() {
4 const [copiedText, setCopiedText] = useState<string | null>(null);
5
6 const copy = async (text: string) => {
7 if (!navigator?.clipboard) {
8 console.warn('Clipboard not supported');
9 return false;
10 }
11
12 try {
13 await navigator.clipboard.writeText(text);
14 setCopiedText(text);
15 return true;
16 } catch (error) {
17 console.warn('Copy failed', error);
18 setCopiedText(null);
19 return false;
20 }
21 };
22
23 return { copiedText, copy };
24}
25
26// Usage example
27function CopyButton({ text }: { text: string }) {
28 const { copiedText, copy } = useCopyToClipboard();
29
30 return (
31 <button onClick={() => copy(text)}>
32 {copiedText === text ? 'Copied!' : 'Copy'}
33 </button>
34 );
35}Organize your team's code snippets with Snippetly. Share knowledge and boost productivity across your organization.