Created
March 30, 2021 12:23
-
-
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)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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