I have a code that copy the text value of a paragraph element in React to the clipboard.
The code is working (copying the value to the clipboard) but is it copying the value plus two newlines into the clipboard.
For example if I want to copy the value '2345678' it will copy:
'2345678
'
import './CopyClipboard.css';
class CopyClipboard extends React.Component {
constructor(props) {
super(props);
this.textContent = null;
this.state = {
copied: false
};
}
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 });
};
initRef = c => (this.textContent = c);
render() {
const { copied } = this.state;
return (
<div className="positioning">
<p onMouseLeave={() => this.setState({ copied: false })} onClick={this.copyToClipboard} ref={this.initRef}>
{this.props.value}
</p>
{copied === false ? <p className="success">Copy to Clipboard</p> : <p className="success">Copied!!!</p>}
</div>
);
}
}
export default CopyClipboard;
maybe someone can understand what am I doing wrong here ?
Thanks!
so I managed to get it working using @ChrisSandvik solution to use clipboard-polyfill
the code:
import React from 'react';
import * as clipboard from "clipboard-polyfill";
import './CopyClipboard.css';
class CopyClipboard extends React.Component {
constructor(props) {
super(props);
this.state = {
copied: false
};
}
copyText = e => {
clipboard.writeText(this.props.value);
this.setState({ copied: true });
};
render() {
const { copied } = this.state;
return (
<div className="positioning">
<p onMouseLeave={() => this.setState({ copied: false })} onClick={this.copyText} ref={this.initRef}>
{this.props.value}
</p>
{copied === false ? <p className="success">Copy to Clipboard</p> : <p className="success">Copied!!!</p>}
</div>
);
}
}
export default CopyClipboard;
EDIT 2:
I found the problem, the value passed was ok, but <p></p> elements have default css that is effecting the value that you will get when you retrieve it.
you can fix it by either using <span> or overriding the <p> default css