Skip to content

Instantly share code, notes, and snippets.

@falmar
Forked from netsi1964/CopyToClipboard.jsx
Created August 11, 2017 12:45
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save falmar/d01bdc890e5cb1c108d80cb66e012d5b to your computer and use it in GitHub Desktop.
Save falmar/d01bdc890e5cb1c108d80cb66e012d5b to your computer and use it in GitHub Desktop.
ReactJS component: Copy to clipboard

ReactJS CopyToClipboard component

The need to copy something to the clipboard can be handled easily using this component: CopyToClipboard.

Using it

  1. Add the component <CopyToClipboard />

This is the simplest form using defaultProps, which will show you how it works. You will want to change the props:

CopyToClipboard.defaultProps = {
	label: "Copy",
	silent: false,
	text: "Set prop 'text' to your text to copy, or add call back function 'onCopy' which returns the value to copy",
	onCopy: txt => {
	  // return "Nothing to copy "+new Date();
	  return txt;
	}
};

Label ("copy")

What to show in the button

silent ("false")

Should a prompt be shown with the copied content?

text ("some default text")

One way to use the component is to provide in a prop the text to copy.

onCopy ("will return value of text prop")

You can provide a function which should then return a text which will be copied to clipboard The function will be called with the value of text property.

Example of use

I have made a ReactJS pen which is using this component.

Feedback

Send your feedback to me on twitter: @netsi1964

class CopyToClipboard extends React.Component {
constructor(props) {
super(props);
}
copy() {
const copyTextarea = this.refs.data;
const { text, onCopy, silent } = this.props;
copyTextarea.value = onCopy.call(this, text);
copyTextarea.select();
try {
let successful = document.execCommand("copy");
let msg = successful ? "successful" : "unsuccessful";
if (!silent) {
prompt("Copying text command was " + msg, copyTextarea.value);
}
} catch (err) {
alert("Oops, unable to copy");
}
}
render() {
let { label } = this.props;
return (
<p>
<button onClick={this.copy.bind(this)}>
{label}
</button>
<textarea ref="data" style={{ position: "absolute", top: "-1000px" }} />
</p>
);
}
}
CopyToClipboard.defaultProps = {
label: "Copy",
silent: false,
text:
"Set prop 'text' to your text to copy, or add call back function 'onCopy' which returns the value to copy",
onCopy: txt => {
// return "Nothing to copy "+new Date();
return txt;
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment