Skip to content

Instantly share code, notes, and snippets.

@akinncar
Created February 1, 2021 16:33
Show Gist options
  • Save akinncar/a9a87537768287fc2c1ed7c7d77d9433 to your computer and use it in GitHub Desktop.
Save akinncar/a9a87537768287fc2c1ed7c7d77d9433 to your computer and use it in GitHub Desktop.
SnackBar Material UI Context Typescript Boilerplate
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 };
@lazaroalvarenga
Copy link

That's greatest! Only one fix on here for work to me: moving typeColor declaration type from Color to AlertColor

@caiqueth
Copy link

caiqueth commented Nov 3, 2022

Very useful! Thank you! 😄

@hm-chirag
Copy link

Good Work

@petrosmm
Copy link

awesome!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment