Published on

How to Change Icon Size on Alert in Material UI for React

Authors
  • Name
    Ripal & Zalak
    Twitter

How to Change Icon Size on Alert in Material UI for React

Material UI provides an Alert component that displays messages with icons. However, resizing the default icon isn't straightforward. In this guide, you'll learn how to adjust the icon size without replacing it.

Why Change the Icon Size?

  • Enhances UI consistency
  • Improves accessibility
  • Matches the design aesthetics

Solution 1: Using makeStyles (MUI v4)

If you're using Material UI v4, you can modify the .MuiAlert-icon class through makeStyles:

import React from 'react'
import Snackbar from '@mui/material/Snackbar'
import Button from '@mui/material/Button'
import Alert from '@mui/material/Alert'
import { makeStyles } from '@mui/styles'

const useStyles = makeStyles({
  cookieAlert: {
    '& .MuiAlert-icon': {
      fontSize: '2rem', // Adjust the size as needed
    },
  },
})

export default function CustomAlert() {
  const classes = useStyles()

  return (
    <Snackbar open={true}>
      <Alert
        className={classes.cookieAlert}
        severity="info"
        action={
          <Button color="inherit" size="small">
            OK
          </Button>
        }
      >
        We use cookies to ensure you the best experience on our website.
      </Alert>
    </Snackbar>
  )
}

Solution 2: Using sx Prop (MUI v5)

For Material UI v5, use the sx prop to apply styles:

import React from 'react'
import Snackbar from '@mui/material/Snackbar'
import Button from '@mui/material/Button'
import Alert from '@mui/material/Alert'

export default function CustomAlert() {
  return (
    <Snackbar open={true}>
      <Alert
        sx={{ '& .MuiAlert-icon': { fontSize: '2rem' } }} // Modify size
        severity="info"
        action={
          <Button color="inherit" size="small">
            OK
          </Button>
        }
      >
        We use cookies to ensure you the best experience on our website.
      </Alert>
    </Snackbar>
  )
}

Alternative: Custom Icons

If you want to replace the icon instead of resizing it, use the iconMapping prop:

import InfoIcon from '@mui/icons-material/Info'

;<Alert severity="info" icon={<InfoIcon fontSize="large" />}>
  Custom Icon Alert
</Alert>

FAQ

1. Can I apply different sizes for different severities?

Yes! Modify the sx prop dynamically:

sx={{
  "& .MuiAlert-icon": {
    fontSize: (theme) => ({
      info: "2rem",
      warning: "2.5rem",
      error: "3rem",
    })[severity]
  }
}}

2. What is the default size of the Alert icon?

The default size is 1.5rem. You can override it as needed.

3. Does this affect performance?

No, since only CSS styles are changed.