material-ui snackbar change colorwith no making a new onefor each color?

Viewed 861

how do i change the color of a snackbar without having to make a new one in material-ui do i have to create a new one for every color? In the example sandbox they have only one color the other ones are static

2 Answers

You don't need to create different components, all you have to do is use hooks to pass properties to modify the component

 <Snackbar open={open} autoHideDuration={6000} onClose={handleClose}>
    <Alert onClose={handleClose} severity={severity}>
    {message}
    </Alert>
    </Snackbar>

Like that you can pass the message you want and the severity you want in one component here is a working example

https://codesandbox.io/s/delicate-frost-itv99

Edit:

As Dekel pointed out the <Alert> is a different component and it is the one reciving the severity and message.

The snackbar doesn't have specific color settings, but the content of the snackbar can be anything you want.

For example - you can put the <Alert> component inside the snackbar, and materia's alert component has multiple values for severity which controls the color of the alert.

This will generate a green alert:

<Snackbar open={open} autoHideDuration={6000} onClose={handleClose}>
  <Alert onClose={handleClose} severity="success">
    This is a success message!
  </Alert>
</Snackbar>

This will generate a red alert:

<Snackbar open={open} autoHideDuration={6000} onClose={handleClose}>
  <Alert onClose={handleClose} severity="error">
    This is a success message!
  </Alert>
</Snackbar>

The green and the red are coming from the <Alert> component.

Related