Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I alter the types for material UI alert component?

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.

like image 861
codeEagle123 Avatar asked Sep 19 '25 10:09

codeEagle123


1 Answers

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>
like image 79
Muller Roufaou Avatar answered Sep 21 '25 01:09

Muller Roufaou