Skip to content

Instantly share code, notes, and snippets.

@yarastqt
Created October 28, 2020 13:02
Show Gist options
  • Select an option

  • Save yarastqt/5fb9f0ea3148076feffc62feca8cb154 to your computer and use it in GitHub Desktop.

Select an option

Save yarastqt/5fb9f0ea3148076feffc62feca8cb154 to your computer and use it in GitHub Desktop.
const useCopyToClipboard = (text) => {
const copyToClipboard = (str) => {
const el = document.createElement('textarea');
el.value = str;
el.setAttribute('readonly', '');
el.style.position = 'absolute';
el.style.left = '-9999px';
document.body.appendChild(el);
const selected =
document.getSelection().rangeCount > 0
? document.getSelection().getRangeAt(0)
: false;
el.select();
const success = document.execCommand('copy');
document.body.removeChild(el);
if (selected) {
document.getSelection().removeAllRanges();
document.getSelection().addRange(selected);
}
return success;
};
const [copied, setCopied] = React.useState(false);
const copy = React.useCallback(() => {
if (!copied) setCopied(copyToClipboard(text));
}, [text]);
React.useEffect(() => () => setCopied(false), [text]);
return [copied, copy];
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment