Skip to content

Instantly share code, notes, and snippets.

@lele85
Created December 29, 2017 09:22
Show Gist options
  • Save lele85/32e967319b42a1fc0e2801aad1984b15 to your computer and use it in GitHub Desktop.
Save lele85/32e967319b42a1fc0e2801aad1984b15 to your computer and use it in GitHub Desktop.
clipboard
import Clipboard from "modules/common/lib/Clipboard";
import React from "react";
export class CopyToClipboard extends React.Component {
constructor() {
super();
this.timeout = null;
this.state = {
copying: false,
success: true
};
this.onCopyClick = this.onCopyClick.bind(this);
}
componentWillUnmount() {
clearTimeout(this.timeout);
this.timeout = null;
this.setState({
copying: false,
success: true
});
}
onCopyClick(e) {
e.preventDefault();
const {
text
} = this.props;
const success = Clipboard.copyToClipboard(text);
this.setState({
copying: true,
success: success
});
this.timeout = setTimeout(() => {
this.timeout = null;
this.setState({
copying: false,
success: true
});
}, 800);
}
render() {
const {
copyChildren,
successChildren,
errorChildren,
} = this.props;
const {
copying,
success
} = this.state;
if (copying && success) {
return successChildren;
}
if(copying && !success) {
return errorChildren;
}
if(!copying) {
return React.cloneElement(
copyChildren,
{onClick: this.onCopyClick}
)
}
return null;
}
}
export default CopyToClipboard;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment