CopyButton.tsx 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102
  1. import React, { useState, FC } from 'react';
  2. import PropTypes from 'prop-types';
  3. import {
  4. makeStyles,
  5. Theme,
  6. createStyles,
  7. Tooltip,
  8. IconButton,
  9. Fade,
  10. } from '@material-ui/core';
  11. interface CopyButtonProps {
  12. className?: string;
  13. icon?: any;
  14. label: string;
  15. value: string;
  16. others?: any;
  17. }
  18. const CopyIcon = (
  19. <svg
  20. width="16"
  21. height="16"
  22. viewBox="0 0 16 16"
  23. fill="none"
  24. xmlns="http://www.w3.org/2000/svg"
  25. >
  26. <path
  27. d="M13.3333 6H7.33333C6.59695 6 6 6.59695 6 7.33333V13.3333C6 14.0697 6.59695 14.6667 7.33333 14.6667H13.3333C14.0697 14.6667 14.6667 14.0697 14.6667 13.3333V7.33333C14.6667 6.59695 14.0697 6 13.3333 6Z"
  28. stroke="#06AFF2"
  29. strokeWidth="2"
  30. strokeLinecap="round"
  31. strokeLinejoin="round"
  32. />
  33. <path
  34. d="M3.33301 9.99992H2.66634C2.31272 9.99992 1.97358 9.85944 1.72353 9.60939C1.47348 9.35935 1.33301 9.02021 1.33301 8.66659V2.66659C1.33301 2.31296 1.47348 1.97382 1.72353 1.72378C1.97358 1.47373 2.31272 1.33325 2.66634 1.33325H8.66634C9.01996 1.33325 9.3591 1.47373 9.60915 1.72378C9.8592 1.97382 9.99967 2.31296 9.99967 2.66659V3.33325"
  35. stroke="#06AFF2"
  36. strokeWidth="2"
  37. strokeLinecap="round"
  38. strokeLinejoin="round"
  39. />
  40. </svg>
  41. );
  42. const CopyButton: FC<CopyButtonProps> = props => {
  43. const { label, icon, className, value, ...others } = props;
  44. const classes = useStyles();
  45. const [tooltipTitle, setTooltipTitle] = useState('Copy');
  46. const handleClick = (v: string) => {
  47. setTooltipTitle('Copied!');
  48. navigator.clipboard.writeText(v);
  49. setTimeout(() => {
  50. setTooltipTitle('Copy');
  51. }, 1000);
  52. };
  53. return (
  54. <Tooltip
  55. title={tooltipTitle}
  56. arrow
  57. placement="top"
  58. TransitionComponent={Fade}
  59. TransitionProps={{ timeout: 600 }}
  60. className={classes.tooltip}
  61. >
  62. <IconButton
  63. aria-label={label}
  64. className={`${classes.button} ${className}`}
  65. onClick={() => handleClick(value || '')}
  66. {...others}
  67. >
  68. {icon || CopyIcon}
  69. </IconButton>
  70. </Tooltip>
  71. );
  72. };
  73. CopyButton.propTypes = {
  74. className: PropTypes.string,
  75. icon: PropTypes.element,
  76. label: PropTypes.string.isRequired,
  77. value: PropTypes.string.isRequired,
  78. others: PropTypes.object,
  79. };
  80. CopyButton.defaultProps = {
  81. label: 'copy button',
  82. value: '',
  83. };
  84. CopyButton.displayName = 'CopyButton';
  85. const useStyles = makeStyles((theme: Theme) =>
  86. createStyles({
  87. root: {},
  88. button: {},
  89. tooltip: {},
  90. })
  91. );
  92. export default CopyButton;