Skip to content

Instantly share code, notes, and snippets.

@GalindoSVQ
Created November 4, 2023 10:59
Show Gist options
  • Save GalindoSVQ/9b1f7547f54faca76502f07745a2e4a8 to your computer and use it in GitHub Desktop.
Save GalindoSVQ/9b1f7547f54faca76502f07745a2e4a8 to your computer and use it in GitHub Desktop.
import * as React from 'react';
function oldSchoolCopy(text) {
const tempTextArea = document.createElement('textarea');
tempTextArea.value = text;
document.body.appendChild(tempTextArea);
tempTextArea.select();
document.execCommand('copy');
document.body.removeChild(tempTextArea);
}
export default function useCopyToClipboard() {
const [state, setState] = React.useState<string | null>(null);
const copyToClipboard = React.useCallback((value: string) => {
const handleCopy = async () => {
try {
if (navigator?.clipboard?.writeText) {
await navigator.clipboard.writeText(value);
setState(value);
} else {
throw new Error('writeText not supported');
}
} catch (e) {
oldSchoolCopy(value);
setState(value);
}
};
handleCopy();
}, []);
return [state, copyToClipboard];
}
@GalindoSVQ
Copy link
Author

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment