I am building a React web app that converts a text into an array. I want the user to click on the final output and be able to copy it on the clipboard.
I am following the of many websites and tutorial. I am very new to ReactJS and I don't know what's wrong with my code!
This is the function I
copyToClipboard() {
const {array} = this.state
const textToCopy = "const myArray =" + JSON.stringify(array)
textToCopy.select()
document.execCommand("copy")
this.setState({copySuccess: true})
}
The function is called by this button. The button works fine:
<button onClick={this.copyToClipboard.bind(this)} id="copy-to-clipboard" className="btn btn-normal">Copy to clipboard</button>
I think the problem is in this part of the function below, but I don't know how to fix it!
textToCopy.select()
document.execCommand("copy")
Link to the whole app + code:
https://codepen.io/Nerdifico/pen/MWKPdNX?editors=0010
const copyToClipboard = (content: any) => {
const el = document.createElement('textarea');
el.value = content;
document.body.appendChild(el);
el.select();
document.execCommand('copy');
document.body.removeChild(el);
};
Here is my solution, it contains 3 steps:
You should use a DOM element from which to copy from. This is an example with textarea. You can't call select on string value.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With