Skip to content

Instantly share code, notes, and snippets.

@armandocanals
Last active April 5, 2019 06:26
Show Gist options
  • Save armandocanals/3f2552f41c9a11ebd1dff6e73f5d0791 to your computer and use it in GitHub Desktop.
Save armandocanals/3f2552f41c9a11ebd1dff6e73f5d0791 to your computer and use it in GitHub Desktop.
Copy button using native browser range
import React from 'react';
class CopyButton extends React.Component {
constructor(props) {
super(props);
this.buttonText = props.buttonText;
this.copyText = props.textToCopy;
this.onCopied = this.onCopied.bind(this);
this.styles = {
border: '1px solid #eee',
borderRadius: 3,
backgroundColor: '#FFFFFF',
cursor: 'pointer',
fontSize: 15,
padding: '3px 10px',
margin: 10
};
}
onCopied(e) {
let node = document.createElement("pre");
node.textContent = this.copyText;
node.style.position = "absolute";
node.style.top = 0;
document.body.appendChild(node);
try {
if (!document.queryCommandSupported('copy')) throw "This client doesn't support the copy command!";
let range = document.createRange();
range.selectNodeContents(node);
let selection = window.getSelection();
selection.removeAllRanges();
selection.addRange(range);
if (document.execCommand('copy')) {
if (typeof this.props.onCopied === 'function') {
this.props.onCopied(e);
}
} else {
throw "document.execCommand('copy') returned false";
}
} catch(err) {
console.error('Unable to copy:', err);
}
document.body.removeChild(node);
}
render() {
return (
<button className='btn primary outline'
onClick={this.onCopied}
style={this.styles}>
{ this.buttonText || this.props.children }
</button>
);
}
}
export default CopyButton;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment