Home > OS >  Why are the custom theme values not working in React component for Material UI v5?
Why are the custom theme values not working in React component for Material UI v5?

Time:01-27

I configured a custom theme for MUI but it's not working. I have followed the exact steps and made sure that nothing is out of place.

Here's what my package.json looks like:

"dependencies": {
    "@emotion/react": "^11.10.5",
    "@emotion/styled": "^11.10.5",
    "@mui/icons-material": "^5.11.0",
    "@mui/material": "^5.11.1",

This is the App component:

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

function App() {
  return (
    <ThemeProvider theme={theme}>
      <Box>
        <Router>
          <Header />
          <Container>
            <Routes>
              <Route path="/" element={<NotesTable />} />
              <Route path="/my-notes" element={<MyNotes />} />
              <Route path="/notes/:noteId" element={<Note />} />
              <Route
                path="/create-note"
                element={<CreateNote key={window.location.pathname} />}
              />
              <Route path="/edit/:noteId" element={<CreateNote />} />
              <Route path="*" element={<NotFound />} />
            </Routes>
          </Container>
        </Router>
        <ToastContainer />
      </Box>
    </ThemeProvider>
  )
}

But when I try to use the primary color in one of the components, it does not work:

<Stack
      direction="row"
      justifyContent="space-between"
      alignItems="center"
      backgroundColor="primary"
      sx={{ height: "70px" }}
    >
      <div onClick={redirectHome} className="logo">
        GIT NOTES
      </div>
      <div className="top-right">
        {location.pathname === "/" && <SearchBar />}
        {user ? (
          <AccountMenu />
        ) : (
          <div className="secondary-button">
            <a href={GITHUB_LOGIN_URL}>Login</a>
          </div>
        )}
      </div>
    </Stack>

Here's the custom theme:

import { createTheme } from "@mui/material"
import { red } from "@mui/material/colors"

export const theme = createTheme({
  palette: {
    primary: {
      main: red[200],
      light: "#bdead9",
    },
    secondary: {
      main: "#35a77d",
    },
  },
})

If I replace "primary" with "red" for example, it works correctly and the background color changes. That means there is something specifically wrong with the custom theme.

What could be the issue?

CodePudding user response:

<Stack sx={{bgcolor: 'primary.main'}}>

Check MUI sx prop

  • Related