- Published on
How to Change Alert Colors in Material UI
- Authors
- Name
- Ripal & Zalak
How to Change Alert Colors in Material UI
Material UI provides an Alert
component with predefined severity colors (success
, error
, warning
, and info
). However, developers often need custom colors for branding or better UI consistency. This guide covers multiple ways to override and customize MUI Alert colors.
Method 1: Using Theme Overrides
The best way to apply global changes to your Alert
component is by using createTheme
and styleOverrides
:
import { createTheme, ThemeProvider } from '@mui/material/styles'
import Alert from '@mui/material/Alert'
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',
},
},
},
},
})
function App() {
return (
<ThemeProvider theme={theme}>
<Alert severity="success">Success Alert</Alert>
<Alert severity="error">Error Alert</Alert>
<Alert severity="warning">Warning Alert</Alert>
<Alert severity="info">Info Alert</Alert>
</ThemeProvider>
)
}
export default App
Method 2: Using Styled Components
You can create a styled version of the Alert
component using MUI’s styled
API:
import { styled } from '@mui/material/styles'
import Alert from '@mui/material/Alert'
const StyledAlert = styled(Alert)({
backgroundColor: '#fde8e9',
color: '#d32f2f',
})
function App() {
return (
<StyledAlert severity="error" variant="filled">
Custom Error Alert
</StyledAlert>
)
}
export default App
Method 3: Inline Styles with Props
If you need a quick customization without modifying global styles, you can pass styles directly using the sx
prop:
function App() {
return (
<Alert severity="warning" sx={{ backgroundColor: '#ffcc00', color: '#000' }}>
Custom Warning Alert
</Alert>
)
}
export default App
Method 4: Custom Component with Dynamic Colors
For fully flexible color options, create a wrapper component that takes custom colors as props:
import Alert from '@mui/material/Alert'
import { styled } from '@mui/material/styles'
const CustomAlert = styled(Alert)(({ background }) => ({
backgroundColor: background || 'inherit',
}))
function App() {
return (
<CustomAlert severity="info" background="#4caf50">
Custom Info Alert
</CustomAlert>
)
}
export default App
FAQ
1. Can I use Tailwind CSS with Material UI Alerts?
Yes, but you’ll need to manually override MUI styles using Tailwind classes via the sx
prop or global styles.
2. Will these methods work in MUI v4?
No, the styleOverrides
feature is available in MUI v5. In MUI v4, you need to use overrides
in the theme configuration.
3. Can I set different colors for dark mode?
Yes, you can use MUI's theme mode detection and apply different colors based on theme.palette.mode
.