CustomSnackBar.tsx 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182
  1. import { forwardRef, FC, SyntheticEvent } from 'react';
  2. import { CustomSnackBarType } from './Types';
  3. import MuiAlert from '@material-ui/lab/Alert';
  4. import { Snackbar, makeStyles, Theme, createStyles } from '@material-ui/core';
  5. import Slide from '@material-ui/core/Slide';
  6. import { TransitionProps } from '@material-ui/core/transitions/transition';
  7. // if we need to use slide component
  8. // snackbar content must use forwardRef to wrapper it
  9. const Alert = forwardRef((props: { [x: string]: any }, ref) => {
  10. return <MuiAlert ref={ref} elevation={6} variant="filled" {...props} />;
  11. });
  12. function SlideTransition(props: TransitionProps) {
  13. return <Slide {...props} direction="left" />;
  14. }
  15. const useStyles = makeStyles((theme: Theme) =>
  16. createStyles({
  17. root: {
  18. maxWidth: '50vh',
  19. wordBreak: 'break-all'
  20. },
  21. topRight: {
  22. [theme.breakpoints.up('md')]: {
  23. top: '72px',
  24. right: theme.spacing(4),
  25. },
  26. top: '72px',
  27. right: theme.spacing(4),
  28. },
  29. })
  30. );
  31. const CustomSnackBar: FC<CustomSnackBarType> = props => {
  32. const {
  33. vertical,
  34. horizontal,
  35. open,
  36. autoHideDuration = 2500,
  37. type,
  38. message,
  39. onClose,
  40. } = props;
  41. const classes = useStyles();
  42. const handleClose = (e: SyntheticEvent<any, Event>, reason: string) => {
  43. // only click x to close or auto hide.
  44. if (reason === 'clickaway') {
  45. return;
  46. }
  47. onClose && onClose();
  48. };
  49. return (
  50. <div>
  51. <Snackbar
  52. anchorOrigin={{
  53. vertical: vertical,
  54. horizontal: horizontal,
  55. }}
  56. key={`${vertical}${horizontal}`}
  57. open={open}
  58. onClose={handleClose}
  59. autoHideDuration={autoHideDuration}
  60. classes={{
  61. anchorOriginTopRight: classes.topRight,
  62. }}
  63. TransitionComponent={SlideTransition}
  64. >
  65. <Alert
  66. onClose={handleClose}
  67. severity={type}
  68. classes={{ root: classes.root }}
  69. >
  70. {message}
  71. </Alert>
  72. </Snackbar>
  73. </div>
  74. );
  75. };
  76. export default CustomSnackBar;