Normal
Normal

Reputation: 3626

Change Appbar backgroundColor in MUI

The default Appbar color is set by MUI to the primary color, which is the blue color. If I wanted to change that color directly using sx={{ background: 'white' }}, then I will lose the feature of the dark theme. In other words, the background color white will stuck even when the MUI dark mode theme is applied. Which is an unwanted behavior.

So, How I can change the background color of the Appbar in the correct way while keeping the support for the dark mode feature of Mui?

Upvotes: 3

Views: 4630

Answers (2)

Normal
Normal

Reputation: 3626

I found the solution, you simply have to use the prop color instead of using the prop sx to change the background color of the Appbar component,

for example:

<Appbar color="default"> 👈 here
   <Toolbar disableGutters sx={{ pl: 3 }}>
      ... etc

Setting the color prop to "default" is going to change the color to white, and when you switch to dark theme, it's going to apply the dark theme automatically for it.

You can use other variants of the color prop as well, ex: primary, success, secondary.

Upvotes: 1

pez
pez

Reputation: 4235

First check the user's preference between a light or dark theme:

import useMediaQuery from '@mui/material/useMediaQuery';
const prefersDarkMode = useMediaQuery('(prefers-color-scheme: dark)')

Then you can set the AppBar's color accordingly:

const appBarColor = prefersDarkMode ? darkColor : lightColor
return <AppBar sx = {{ background: appBarColor }} />

You may also choose to check the value of theme.palette.mode to determine the color in that manner.

useMediaQuery

prefers-color-scheme

Upvotes: 3

Related Questions