Search code examples
reactjsmaterial-ui

Material UI Theme not being applied in NextJS


I'm experiencing an error using Material UI where even after applying the theme to the provider, the changes are not reflected, always bringing its "default" version

So for example, my theme creation is like this:

import { createTheme } from '@mui/material/styles';
import { Roboto } from 'next/font/google';

const roboto = Roboto({
    weight: ['300', '400', '500', '700'],
    subsets: ['latin'],
    display: 'swap',
});

const theme = createTheme({
    palette: {
        mode: 'dark',
    },
    cssVariables: true,
    typography: {
        fontFamily: roboto.style.fontFamily,
    },
});

export default theme;

When consulting it in this way:

const theme = useTheme();

console.log(theme);

The return shows that the mode is light. I don't get any particular error, I just can't update the theme, it always returns the default version.

I'm using the following libraries:

"next": "14.2.18", "react": "18.3.1", "@mui/material": "6.1.9",

I tried to follow this example:

https://github.com/manakuro/nextjs-styled-component-material-ui-example

I also tried to follow the docs for integration with nextjs and dark mode:

https://mui.com/material-ui/integrations/nextjs/ https://mui.com/material-ui/customization/dark-mode/


Solution

  • If you are not sure from where to import the correct modules, you can check the documentation.

    This one for example: https://mui.com/material-ui/integrations/nextjs/#font-optimization.

    import { ThemeProvider } from '@mui/material/styles';

    You can see that the ThemeProvider is imported from @mui/material/styles.

    You are importing it from @mui/styles

    Replace @mui/styles with @mui/material/styles