JAVASCRIPT
React Hook: useCopyToClipboard for Easy Text Copying
A custom React hook facilitating one-click copy functionality. `useCopyToClipboard` simplifies implementing features to copy text to the user's clipboard with status feedback.
import { useState, useCallback } from 'react';
function useCopyToClipboard() {
const [copiedText, setCopiedText] = useState(null);
const [error, setError] = useState(null);
const copy = useCallback(async (text) => {
if (!navigator?.clipboard) {
console.warn('Clipboard not supported');
setError(new Error('Clipboard not supported'));
return false;
}
try {
await navigator.clipboard.writeText(text);
setCopiedText(text);
setError(null);
return true;
} catch (err) {
console.error('Failed to copy text: ', err);
setError(err);
setCopiedText(null);
return false;
}
}, []);
return [copiedText, copy, error];
}
How it works: The `useCopyToClipboard` hook provides functionality to copy text to the user's clipboard. It manages state for the `copiedText` and any potential `error`. The `copy` function, wrapped in `useCallback` for performance, checks for clipboard API support and then uses `navigator.clipboard.writeText` to perform the copy operation. It updates the `copiedText` state on success and `error` state on failure, returning a boolean indicating success or failure. This allows components to easily implement copy-to-clipboard features with feedback.