I'm using ReactJS and when a user clicks a link I want to copy some text to the clipboard.
I am using Chrome 52 and I do not need to support any other browsers.
I can't see why this code does not result in the data being copied to the clipboard. (the origin of the code snippet is from a Reddit post).
Am I doing this wrong? Can anyone suggest is there a "correct" way to implement copy to clipboard using reactjs?
copyToClipboard = (text) => {
console.log('text', text)
var textField = document.createElement('textarea')
textField.innerText = text
document.body.appendChild(textField)
textField.select()
document.execCommand('copy')
textField.remove()
}
For those people who are trying to select from the DIV instead of the text field, here is the code. The code is self-explanatory but comment here if you want more information:
here is my code:
I've taken a very similar approach as some of the above, but made it a little more concrete, I think. Here, a parent component will pass the url (or whatever text you want) as a prop.
If you want to select from the DIV instead of the text field, here is the code. The "code" is the value that has to be copied
Here's another use case, if you would like to copy the current url to your clipboard:
Define a method
Call that method