@supunlakmal/hooks
Version:
A collection of reusable React hooks
53 lines • 2.06 kB
JavaScript
import { useState, useCallback } from 'react';
/**
* Custom hook for copying text to the clipboard.
* Uses the modern Clipboard API (`navigator.clipboard.writeText`) with a fallback.
*
* @returns {UseCopyToClipboardReturn} A tuple containing the copy status and the copy function.
*/
export const useCopyToClipboard = () => {
const [status, setStatus] = useState(null);
const copy = useCallback(async (text) => {
// Use the modern Clipboard API if available
if (navigator.clipboard && navigator.clipboard.writeText) {
try {
await navigator.clipboard.writeText(text);
setStatus(true);
}
catch (error) {
console.error('Failed to copy text using Clipboard API:', error);
setStatus(false);
}
}
else {
// Fallback for older browsers
try {
const textArea = document.createElement('textarea');
textArea.value = text;
// Prevent scrolling to bottom
textArea.style.position = 'fixed';
textArea.style.top = '-9999px';
textArea.style.left = '-9999px';
document.body.appendChild(textArea);
textArea.focus();
textArea.select();
const successful = document.execCommand('copy');
document.body.removeChild(textArea);
if (successful) {
setStatus(true);
}
else {
throw new Error('document.execCommand("copy") failed');
}
}
catch (error) {
console.error('Failed to copy text using fallback method:', error);
setStatus(false);
}
}
// Optional: Reset status after a delay
setTimeout(() => setStatus(null), 2000); // Reset after 2 seconds
}, []);
return [status, copy];
};
//# sourceMappingURL=useCopyToClipboard.js.map