I am relatively new to Typescript and I have created a snackbar component using React Context and when I try to set the Alert severity, I get this error "Type 'string' is not assignable to type 'Color | undefined'." I do have the type set to a string however, I cannot seem to figure out how to give it a type of Color. Here is my Alert component:
const AppAlert = () => {
const alertContext = useContext(AlertContext);
return (
<div>
<Snackbar open={alertContext.snackbarOpen}>
<Alert severity={alertContext.snackbarType} variant="filled">
{alertContext.snackbarMessage}
</Alert>
</Snackbar>
</div>
);
};
export default AppAlert;
Here are my Alert prop types:
interface AlertProps {
snackbarOpen: boolean;
snackbarType: string;
snackbarMessage: string;
setAlert: (type: string, message: string) => void;
}
I hope I was specific enough as I am still working on understanding TS.
The severity of Material-ui alerts can be one of four types 'error' | 'info' | 'success' | 'warning'
according to the documentation material-ui.com/api/alert. The problem you are having is because the severity property of your Alert
component has been assigned an undefined
value from your alertContext.snackbarType
. To avoid errors if something goes wrong, it would be good practice to set a default severity type as follows:
<Alert severity={alertContext?.snackbarType || 'warning'} variant="filled">
{alertContext?.snackbarMessage}
</Alert>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With