CustomButton.tsx 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110
  1. import { Button, ButtonProps, Tooltip, Theme } from '@mui/material';
  2. import { makeStyles } from '@mui/styles';
  3. const buttonStyle = makeStyles((theme: Theme) => ({
  4. button: {
  5. padding: theme.spacing(1, 3),
  6. textTransform: 'initial',
  7. fontWeight: 'bold',
  8. },
  9. textBtn: {
  10. color: theme.palette.primary.main,
  11. padding: theme.spacing(1),
  12. '&:hover': {
  13. backgroundColor: theme.palette.primary.main,
  14. color: theme.palette.background.paper,
  15. },
  16. },
  17. containedBtn: {
  18. color: theme.palette.background.paper,
  19. backgroundColor: theme.palette.primary.main,
  20. boxShadow: 'initial',
  21. fontWeight: 'bold',
  22. lineHeight: '24px',
  23. '&:hover': {
  24. backgroundColor: theme.palette.primary.dark,
  25. boxShadow: 'initial',
  26. },
  27. },
  28. containedSecondary: {
  29. backgroundColor: '#fc4c02',
  30. '&:hover': {
  31. backgroundColor: '#fc4c02',
  32. },
  33. },
  34. disabledBtn: {
  35. pointerEvents: 'none',
  36. },
  37. }));
  38. // props types same as Material Button
  39. const CustomButton = (
  40. props: ButtonProps & {
  41. tooltip?: string;
  42. tooltipPlacement?:
  43. | 'bottom'
  44. | 'left'
  45. | 'right'
  46. | 'top'
  47. | 'bottom-end'
  48. | 'bottom-start'
  49. | 'left-end'
  50. | 'left-start'
  51. | 'right-end'
  52. | 'right-start'
  53. | 'top-end'
  54. | 'top-start'
  55. | undefined;
  56. }
  57. ) => {
  58. const classes = buttonStyle();
  59. const { tooltip, tooltipPlacement, disabled, ...otherProps } = props;
  60. // wrap a span to let disabled elements show tooltip
  61. const btn = (
  62. <Button
  63. classes={{
  64. root: classes.button,
  65. text: classes.textBtn,
  66. contained: classes.containedBtn,
  67. containedSecondary: classes.containedSecondary,
  68. disabled: classes.disabledBtn,
  69. }}
  70. disabled={disabled}
  71. {...otherProps}
  72. >
  73. {props.children}
  74. </Button>
  75. );
  76. return (
  77. <>
  78. {/*
  79. add span to let disabled elements show tooltip
  80. see https://material-ui.com/zh/components/tooltips/#disabled-elements
  81. */}
  82. {tooltip ? (
  83. <Tooltip title={tooltip} placement={tooltipPlacement}>
  84. {disabled ? <span>{btn}</span> : btn}
  85. </Tooltip>
  86. ) : (
  87. <Button
  88. classes={{
  89. root: classes.button,
  90. text: classes.textBtn,
  91. contained: classes.containedBtn,
  92. containedSecondary: classes.containedSecondary,
  93. }}
  94. {...otherProps}
  95. >
  96. {props.children}
  97. </Button>
  98. )}
  99. </>
  100. );
  101. };
  102. export default CustomButton;