I am trying to create copy to Clipboard Component. Here is my code:
import React from 'react';
import logo from './logo.svg';
import './App.css';
class CopyClipboard extends React.Component {
constructor(props) {
super(props);
this.state = { copySuccess: 'Copy to Clipboard!' }
}
copyToClipboard = (e) => {
this.textContent.select();
document.execCommand('copy');
e.target.focus();
this.setState({ copySuccess: 'Copied to Clipboard!' });
};
render() {
return (
<div class="positioning">
{
//if i need
}
<p onClick={this.copyToClipboard} ref={(c) => (this.textContent = c)}>yotam@gmail.com</p>
<div class="success">{this.state.copySuccess}</div>
</div>
);
}
}
export default CopyClipboard;
I get Parsing error: Unexpected token
error. But if i use input
tag then its work fine. Where i have done wrong?
For p tag, you can't use .select
.
You need to use selectNode
and addRange
Try something like this for the selection function
copyToClipboard = async e => {
window.getSelection().removeAllRanges();
var range = document.createRange();
range.selectNode(this.textContent);
window.getSelection().addRange(range);
document.execCommand("copy");
window.getSelection().removeAllRanges();
this.setState({ copied: true });
};
Click here for a working example too
Also check out this answer to select text between non input tags.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.