How to Use and Style the MUI Alert Component

The Material-UI Alert component is one of the simpler components in the MUI library. However, understanding how to display it, how to customize the styling, how to control the icons in the Alert can be tricky.

In this example we will create the following Alert:

Custom MUI Alert example
Custom MUI Alert example

Notice how the icon is not the typical error or warning icon and has a different color. The close button hover text is customized. These are easy customizations if you know the correct prop to use, and we will explore this in detail below.

There is a Code Sandbox link to a live example in the Resources section.

Material-UI Alert in a Dialog Component

The first decision with Alert components is: how should they be ‘popped out’ and displayed to the user?

Two common wrapping components are the MUI Snackbar and the MUI Dialog component. The Snackbar has a notification banner feel to it, while the dialog requires interaction to close. In this example I will use a Dialog component, but the concepts are very similar.

export default function CustomAlert() {
  const [open, setOpen] = React.useState(false);

  const handleClick = () => {
    setOpen(!open);
  };

  return (
    <>
      <Button onClick={handleClick} variant="outlined">
        Open Alert!
      </Button>
      <Dialog open={open} onClose={handleClick}>
        <Alert

          //props go here
        >
          <AlertTitle>Danger!</AlertTitle>
          The "Close" button does not work.
        </Alert>
      </Dialog>
    </>
  );
}

(I removed the Alert props for brevity.)

Notice how the Dialog simply wraps the Alert. Dialogs and Snackbars both need to have their open state controlled somehow. A common method is to use the useState hook.

When a user clicks on the mask of the Dialog, that triggers the close event for the modal. I made that event call the same click handler as the Button click so that the open state value would be updated to false when onClose is fired.

Material-UI Alert Width and Styling

Width can easily be customized by setting width in the sx prop. You likely also want to set a margin value, such as 'auto' for horizontal centering.

In the code below, I commented out the width and margin. These will not have the intended effects inside of a Dialog modal. Instead, the Dialog controls the sizing of it’s content.

<Alert
  sx={{
    // width: '80%',
    // margin: 'auto',

    // backgroundColor: 'green'
  }}
  severity="warning"
  color="error"
>
</Alert>

You can also use the sx prop to control other styling such as background color. However, most color styling should be set with the built-in props of severity and color.

There are four values (success, info, warning, error) that come with default color schemes. Setting severity sets the color scheme and icon, but you can override the color scheme by setting the color prop to a different scheme value. In my example, I set severity to "warning", but color to "error".

If you did choose to use the sx prop for styling, you can get an understanding of some of the available classes from this screenshot of the DOM. Notice how color="error" has added the MuiAlert-standardError class.

MUI Alert DOM
MUI Alert DOM

Material-UI Alert Icon and Close

We saw above how to override color styling. MUI also gives a handy prop for overriding the icon visible before the Alert Message. The prop is called icon (not surprising).

In my example I set the icon to the following:

<Alert
  icon={<AccessAlarmIcon />}

  sx={{
    "& .MuiAlert-icon": {
      color: "blue"
    }

  }}
  onClose={() => {}}
  closeText="Doesn't Work!"
>

This override the typical warning triangle icon with an alarm clock icon. Additionally I added a nested selector to change the color of the icon. I found the class .MuiAlert-icon by examining the DOM.

Next up was the close text. I don’t actually need an onClose handler at the Alert level. The Dialog handles closing in my demo. However, if I did not set a value for the onClose handler then the close icon would not appear (and I wouldn’t get a chance to play with it for this article 🙂 ).

The closeText prop simply sets the text in the close icon tooltip. Also, if you want to style the close icon, use this nested selector: "& .MuiAlert-action".

If I wanted my Alert to close automatically, I would set a timeout in a useEffect hook. The useEffect hook would observe the open value and, if the value was true, a timeout would begin and after the designated time then open would be set to false. This would close the Dialog and make the Alert disappear without any user interaction.

However, this is more like Snackbar behavior than Dialog behavior, so I have not implemented it in my demo.

Materail-UI Alert Message

The MUI Alert message text can be passed in as though it was a child of the Alert component.

Additionally, there is one support component called AlertTitle that can be used to add lightly styled title text to the Alert. By default the AlertTitle has font weight of 500 and font size of 1rem.

<Alert>
  <AlertTitle>Danger!</AlertTitle>
  The "Close" button does not work.
</Alert>
MUI AlertTitle DOM
MUI AlertTitle DOM

Resources

Code Sandbox Link

MUI Alert Docs

Share this post:

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.