JAVASCRIPT
React useCopyToClipboard Hook for Text Copying
Implement a custom React hook to easily copy text to the user's clipboard, providing feedback on the success or failure of the operation.
import { useState } from 'react';
function useCopyToClipboard() {
const [copiedText, setCopiedText] = useState(null);
const copy = 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.error('Failed to copy!', error);
setCopiedText(null);
return false;
}
};
return [copiedText, copy];
}
How it works: This useCopyToClipboard hook simplifies copying text to the clipboard. It returns the `copiedText` state and a `copy` function. The `copy` function attempts to use the `navigator.clipboard.writeText` API to copy the given text. It handles cases where the clipboard API is not supported and provides feedback on the success or failure of the operation, updating the `copiedText` state accordingly.