Home > Enterprise >  passing default theme in material UI5
passing default theme in material UI5

Time:03-17

can somebody explain how pass in the defauklt theme in Material UI5

in Material UI6 i use to do it like this

const useStyles = makeStyles((theme) => ({
  home: {
    display: "flex",
    paddingTop: "8rem",
    width: "100vw",
    height: "100vh",
    backgroundColor: theme.palette.primary.dark,
    color: "white",
  },
}));

but as i got throught M-UI5 docs (as far as i found) there is no explanation on how it can be done , the only part they mention about makeStyle it contains this code in this page docs

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

 const theme = createTheme();
 const useStyles = makeStyles((theme) => ({
   background: theme.palette.primary.main,
 }));
 function Component() {
   const classes = useStyles();
   return <div className={classes.root} />
 }

 // In the root of your app
 function App(props) {
-  return <Component />;
   return <ThemeProvider theme={theme}><Component {...props} /></ThemeProvider>;
 }

so am i suppose to run createTheme() on every component to get the theme? , apology if i missed out an obvious thing in the docs , probably coz my poor english

CodePudding user response:

The part you are missing is from this part of the migration guide: https://mui.com/material-ui/guides/migration-v4/#style-library.

if you are using JSS style overrides for your components (for example overrides created by makeStyles), you will need to take care of the CSS injection order. To do so, you need to have the StyledEngineProvider with the injectFirst option at the top of your component tree.

Without this, the default styles for the MUI Card in your About component win over the styles specified via classes.about where the styles overlap (e.g. background).

Changing your AllProviders component to the following (just adding <StyledEngineProvider injectFirst>) fixes it:

import React from "react";
import CountriesProvider from "./countries-context";
import QuestionsProvider from "./questions-context";
import {
  ThemeProvider,
  createTheme,
  StyledEngineProvider
} from "@mui/material/styles";
const theme = createTheme();

const AllProviders = (props) => {
  return (
    <StyledEngineProvider injectFirst>
      <QuestionsProvider>
        <ThemeProvider theme={theme}>
          <CountriesProvider>{props.children}</CountriesProvider>
        </ThemeProvider>
      </QuestionsProvider>
    </StyledEngineProvider>
  );
};

export default AllProviders;

https://codesandbox.io/s/funny-flower-w9dzen?file=/src/store/AllProviders.js:303-342

The theme was being passed in fine without this change (otherwise you would have had errors when it tried to access parts of the theme), but the CSS injection order was not correct.

  • Related