Skip to content

Instantly share code, notes, and snippets.

@derigible
Created March 30, 2021 12:23
Show Gist options
  • Save derigible/e1a39ef8bb6c4bed3a35f0047585210f to your computer and use it in GitHub Desktop.
Save derigible/e1a39ef8bb6c4bed3a35f0047585210f to your computer and use it in GitHub Desktop.
Copy a text field to the clipboard (used in react, but can be extended to other frameworks)
const copyToClipboard = textRef => e => {
e.target.focus();
let text = textRef.current.value;
if (navigator && navigator.clipboard) {
navigator.clipboard.writeText(text);
} else {
// Safari support
let element = document.createElement('a');
element.setAttribute('href', text);
element.textContent = text;
document.body.appendChild(element);
let range;
if (document.selection) {
range = document.body.createTextRange();
range.moveToElementText(element);
range.select();
} else if (window.getSelection) {
range = document.createRange();
range.selectNode(element);
window.getSelection().removeAllRanges();
window.getSelection().addRange(range);
}
document.execCommand('copy');
element.remove();
}
textRef.current.select();
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment