JAVASCRIPT
Copy Text to Clipboard with useCopyToClipboard
Implement a robust `useCopyToClipboard` React hook for easily copying any text to the user's clipboard, providing feedback on success or failure.
import { useState, useCallback } from 'react';
const useCopyToClipboard = () => {
const [copiedText, setCopiedText] = useState(null);
const copy = useCallback(async (text) => {
if (!navigator?.clipboard) {
console.warn('Clipboard not supported');
return false;
}
try {
await navigator.clipboard.writeText(text);
setCopiedText(text);
return true;
} catch (error) {
console.warn('Copy failed', error);
setCopiedText(null);
return false;
}
}, []);
return [copiedText, copy];
};
export default useCopyToClipboard;
How it works: The `useCopyToClipboard` hook provides a convenient way to copy text to the user's clipboard programmatically. It returns the last successfully copied text and a `copy` function. The `copy` function attempts to write the provided text to the clipboard using the `navigator.clipboard.writeText` API, handling potential errors and updating the `copiedText` state accordingly. It's ideal for features like 'copy link' or 'copy code snippet'.