2

I was trying to upgrate material v5(from v4). As per documentation , it is recommended to use Styled or sx API but I wanted to use makeStyles approach as in v4. Even though it is deprecated in v5 but can be used(as per documentation). But I am unable to get theme variable inside makeStyles callback function causing cann't access property of undefined(eg. theme.breakpoints.between...)

import makeStyles from '@mui/styles/makeStyles';
const useStyles = makeStyles((theme) => ({
   // here theme variable is undefined
  appBar: {
    backgroundColor: "white",
    height: "60px",
    padding: "0px 5em",
    [theme.breakpoints.between("xs", 'lg')]: {
      padding: "0px",
    },
  },
 .......

Here is my index.js

import { ThemeProvider, StyledEngineProvider } from "@mui/material/styles";
import theme from "./theme/theme"

ReactDOM.render(
  <React.StrictMode>
    <StyledEngineProvider injectFirst>
      <ThemeProvider theme={theme}>
        <CssBaseline />
        <App />
      </ThemeProvider>
    </StyledEngineProvider>
  </React.StrictMode>,
  document.getElementById("root")
);

theme.js

import { createTheme, responsiveFontSizes, adaptV4Theme } from "@mui/material/styles";
import baseTheme from "./baseTheme";

let theme = createTheme(adaptV4Theme(baseTheme));
theme = responsiveFontSizes(theme);

export default theme;

Also I noticed, StyledEngineProvider is not being property imported(followed this)

enter image description here

package.json

    "@emotion/react": "^11.5.0",
    "@emotion/styled": "^11.3.0",
    "@fortawesome/fontawesome-svg-core": "^1.2.32",
    "@fortawesome/free-solid-svg-icons": "^5.15.1",
    "@fortawesome/react-fontawesome": "^0.1.13",
    "@mui/icons-material": "^5.1.0",
    "@mui/lab": "^5.0.0-alpha.54",
    "@mui/material": "^5.1.0",
    "@mui/styles": "^5.1.0",

Do I have to install additional package to make it working?

1 Answers1

1

Okay, just had this problem. The makeStyles and styled uses a different context to get theme. In order for your makeStyles to access the theme you need import { ThemeProvider } from '@mui/styles'. But to use styled(), you need import { ThemeProvider } from '@mui/material'.

And if you use both styled() AND makeStyles for migration, you need to have BOTH of those theme providers....

pipipi1122
  • 91
  • 3