MUI createTheme is not properly passing theme to MUI components
Solution 1:
Change this line:
import { ThemeProvider } from "@mui/styles";
To:
import { ThemeProvider } from "@mui/material/styles";
Reason: There are 2 ThemeProvider
s here
-
The one from
@mui/styles
: ThisThemeProvider
does send theTheme
object down via context, it works fine, you can still access it using theuseTheme
hook:
const theme = useTheme();
return <Box sx={{ width: 10, height: 10, bgcolor: theme.palette.primary.main }} />
-
The one from
@mui/material/styles
: ThisThemeProvider
is a wrapper of the above, but it also injects the theme to theStyledEngineThemeContext.Provider
, which allows you to access the theme when using MUI API (sx
prop/styled()
). The problem here is that theButton
andMenu
components uses thestyled()
API under-the-hood so theThemeProvider
needs to be imported from@mui/material/styles
to make it work.
return <Box sx={{ width: 10, height: 10, bgcolor: 'primary.main' }} />
Related answers
- Difference between @mui/material/styles and @mui/styles?
- Cannot use palette colors from MUI theme
- MUI - makeStyles - Cannot read properties of undefined
- Material UI Dark Mode