javascriptreactjsmaterial-uithemesthemeprovider

ThemeProvider does not inject theme


I created a them using createTheme from @mui/material/styles, and then I tried to inject the theme using ThemeProvider from @mui/material/styles.

This is my theme:

export const darkTheme = createTheme({
  palette: {
    mode: "dark",
    primary: {
      main: "#12284c",
    },
  },
});

This is where I used ThemeProvider

function App() {
  console.log(darkTheme);
  return (
    <ThemeProvider theme={darkTheme}>
      <Routes>
        <Route path="/" element={<MainLayout />}>
          <Route index element={<Home />} />
        </Route>
      </Routes>
    </ThemeProvider>
  );
}


This is my home component

const Home = ({ theme }) => {
  console.log("🚀 ~ file: Home.js:4 ~ Home ~ theme:", theme);
  return <div>Home</div>;
};

when I log the theme it is undefined. However, I can access the them using useTheme().

How can I fix this problem. I want to receive theme as props in my entire application.


Solution

  • There's no reason to be passing the theme prop through to any components. Use the useTheme() hook for accessing the theme. It's better to use the hook in the places you need to rather than drilling the prop through down to every component you need it on.

    If however you feel like using props (I would discourage that), the issue is that you're not passing the theme prop.

        <Route path="/" element={<MainLayout />}>
            <Route index element={<Home />} />
        </Route>
    

    If you want the theme prop to be accessible you have to modify the element for your index route like so:

    <Route index element={<Home theme={darkTheme} />} />