Home > Enterprise >  Change Appbar backgroundColor in MUI
Change Appbar backgroundColor in MUI

Time:05-14

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?

CodePudding user response:

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

  • Related