Created
February 1, 2021 16:33
-
-
Save akinncar/a9a87537768287fc2c1ed7c7d77d9433 to your computer and use it in GitHub Desktop.
SnackBar Material UI Context Typescript Boilerplate
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { Snackbar } from '@material-ui/core'; | |
import { Alert, Color } from '@material-ui/lab'; | |
import React, { createContext, useContext } from 'react'; | |
type SnackBarContextActions = { | |
showSnackBar: (text: string, typeColor: Color) => void; | |
}; | |
const SnackBarContext = createContext({} as SnackBarContextActions); | |
interface SnackBarContextProviderProps { | |
children: React.ReactNode; | |
} | |
const SnackBarProvider: React.FC<SnackBarContextProviderProps> = ({ | |
children, | |
}) => { | |
const [open, setOpen] = React.useState<boolean>(false); | |
const [message, setMessage] = React.useState<string>(''); | |
const [typeColor, setTypeColor] = React.useState<Color>('info'); | |
const showSnackBar = (text: string, color: Color) => { | |
setMessage(text); | |
setTypeColor(color); | |
setOpen(true); | |
}; | |
const handleClose = () => { | |
setOpen(false); | |
setTypeColor('info'); | |
}; | |
return ( | |
<SnackBarContext.Provider value={{ showSnackBar }}> | |
<Snackbar | |
open={open} | |
autoHideDuration={6000} | |
anchorOrigin={{ vertical: 'top', horizontal: 'center' }} | |
onClose={handleClose}> | |
<Alert onClose={handleClose} severity={typeColor}> | |
{message} | |
</Alert> | |
</Snackbar> | |
{children} | |
</SnackBarContext.Provider> | |
); | |
}; | |
const useSnackBar = (): SnackBarContextActions => { | |
const context = useContext(SnackBarContext); | |
if (!context) { | |
throw new Error('useSnackBar must be used within an SnackBarProvider'); | |
} | |
return context; | |
}; | |
export { SnackBarProvider, useSnackBar }; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Good Work