CopyToClipboard.tsx 1.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. import React, { PureComponent, ReactNode } from 'react';
  2. import ClipboardJS from 'clipboard';
  3. interface Props {
  4. text: () => string;
  5. elType?: string;
  6. onSuccess?: (evt: any) => void;
  7. onError?: (evt: any) => void;
  8. className?: string;
  9. children?: ReactNode;
  10. }
  11. export class CopyToClipboard extends PureComponent<Props> {
  12. clipboardjs: ClipboardJS;
  13. myRef: any;
  14. constructor(props: Props) {
  15. super(props);
  16. this.myRef = React.createRef();
  17. }
  18. componentDidMount() {
  19. const { text, onSuccess, onError } = this.props;
  20. this.clipboardjs = new ClipboardJS(this.myRef.current, {
  21. text: text,
  22. });
  23. if (onSuccess) {
  24. this.clipboardjs.on('success', evt => {
  25. evt.clearSelection();
  26. onSuccess(evt);
  27. });
  28. }
  29. if (onError) {
  30. this.clipboardjs.on('error', evt => {
  31. console.error('Action:', evt.action);
  32. console.error('Trigger:', evt.trigger);
  33. onError(evt);
  34. });
  35. }
  36. }
  37. componentWillUnmount() {
  38. if (this.clipboardjs) {
  39. this.clipboardjs.destroy();
  40. }
  41. }
  42. getElementType = () => {
  43. return this.props.elType || 'button';
  44. };
  45. render() {
  46. const { elType, text, children, onError, onSuccess, ...restProps } = this.props;
  47. return React.createElement(
  48. this.getElementType(),
  49. {
  50. ref: this.myRef,
  51. ...restProps,
  52. },
  53. this.props.children
  54. );
  55. }
  56. }