简体   繁体   中英

How do I access the theme object in Material UI when using React?

There was a recent upgrade in Material UI (@mui) and I'm having trouble accessing the theme object (see below code). The below is incredibly easy code, but it's not working. After 5 hours on this, I'm hoping someone can help me pinpoint the issue.

The error I get is that React can't access "theme" so the property theme.palette.common.black can't be read.

import React from "react";

import { Typography } from "@mui/material";
import { createTheme, ThemeProvider } from "@mui/material/styles";
import { makeStyles, createStyles } from "@mui/styles";

const useStyles = makeStyles((theme) =>
  createStyles({
    monster: {
      backgroundColor: theme.palette.common.black,
    },
  })
);

const theme = createTheme();

function Header(props) {
  const classes = useStyles();

  return (
    <ThemeProvider theme={theme}>
      <Typography variant="h1" className={classes.monster}>
        Hi
      </Typography>
    </ThemeProvider>
  );
}

export default Header;

The example in the documentation is this:

import React from "react";

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

const theme = createTheme();

const useStyles = makeStyles((theme) => ({
  root: {
    color: theme.palette.primary.main,
  },
}));

const Header = (props) => {
  const classes = useStyles();
  return (
    <ThemeProvider theme={theme}>
      <div {...props} className={classes.root}>
        Hello
      </div>
    </ThemeProvider>
  );
};

export default Header;

But when I run this code, I get this error message:

TypeError: Cannot read properties of undefined (reading 'primary')
(anonymous function)
src/components/Header/Header.js:13
  10 | 
  11 | const useStyles = makeStyles((theme) => ({
  12 |   root: {
> 13 |     color: theme.palette.primary.main,
  14 |   },
  15 | }));
  16 | 

You should defined type file that specify the theme in makeStyles which has DefaultTheme interface extends from Theme interface.

For example is TS project you can:


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

declare module '@mui/styles/defaultTheme' {
  // eslint-disable-next-line @typescript-eslint/no-empty-interface
  interface DefaultTheme extends Theme {}
}


The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM