Material UI Alerts using custom colors

Viewed 5317

Can I set a custom color for a MUI Alert component? The docs suggest that the only color options are the four that match the four severity props.

4 Answers

It's possible. Quoting the API docs:

You can override the style of the component thanks to one of these customization points:

  • With a rule name of the classes object prop.
  • With a global class name.
  • With a theme and an overrides property.

A crude example in this codesandbox

A simple approach would be:

const useStyles = makeStyles((theme) => ({
  myAlert: {
    color: "#ffffff",
    backgroundColor: "#000000"
  }
});

function MyCustomAlert() {
    const classes = useStyles();

    return (
        <Alert severity="error" className={classes.myAlert}>
            <AlertTitle>Error</AlertTitle>
            {"I am an error message !"}
        </Alert>
    );
}

For MUI V5 in case someone is looking to change the background color in the theme this worked for me.

export const theme = createTheme({
  components: {
    MuiAlert: {
      styleOverrides: {
        standardSuccess: {
          backgroundColor: 'green',
          color: 'white'
        },
        standardError: {
          backgroundColor: 'red',
          color: 'white'
        },
        standardWarning: {
          backgroundColor: 'orange',
          color: 'white'
        },
        standardInfo: {
          backgroundColor: 'grey',
          color: 'black'
        }
      }
    },
    
  },
});

And is working by setting the variant:

<Alert severity="success">Success</Alert>
<Alert severity="error">Error</Alert>
<Alert severity="warning">Warning</Alert>
<Alert severity="info">Info</Alert>

I guess another option, if you don't wanna deal with css classes, could be:

(using mui v5 and typescript)

first u define your styled component:

interface IAlert extends AlertProps {
      background?: string
}
    
export const Alert = styled(MUIAlert)<IAlert>(({ background }) => ({
    background,
}))

then, on your component that uses the Alert:

const Component = ({type}) => {
  ...
  const CUSTOM_COLORS_MAPPING = {
    success: palette.success[500],
    info: palette.secondary[500],
    error: palette.error[500],
    warning: palette.warning[500],
  }

  return (
    ...
    <Alert severity={type} background={CUSTOM_COLORS_MAPPING[type]}>
      {message}
    </Alert>
  )
Related