Petar Ivcec
Petar Ivcec

Reputation: 756

not able to pass theme to "@mui/system" styled()

I am attempting to pass a theme by doing:

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

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

which I them attempt to read by doing:

import { styled } from "@mui/system";

type StyledTabProps = {
  isActive: boolean;
};

const StyledTab = styled("div", {
  shouldForwardProp: (prop) => prop !== "isActive"
})<StyledTabProps>(({ theme, isActive }) => {
  console.log("theme", theme);
  return {
    color: isActive ? "red" : "blue"
  };
});

the theme which I attempt to pass is different from the one that ends up getting console.logged (is missing properties in palette object)

code sandbox of the issue can be found here:

https://codesandbox.io/s/wandering-https-ubhqs?file=/src/Main.tsx

Upvotes: 0

Views: 1414

Answers (1)

hotcakedev
hotcakedev

Reputation: 2515

You just need to use ThemeProvider from @mui/material/styles, not from @mui/styles. Then it would work.

Please refer to this

// index.tsx

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

...

And also MUI v5 theme structure is a bit different not exactly the same to the v4.

You could not use adaptV4Theme, just update the theme structure, but please define some custom types for it.

(The codesandbox says adaptV4Theme is deprecated somehow.)

For example, you used overrides option for the theme object, but it is removed so you need to use components instead of it. https://mui.com/guides/migration-v4/#theme-structure

...
// styles/theme.ts

export default createTheme(
  {
    ...
    components: {
      MuiInputBase: {
        root: {
        ...
  }
...

Upvotes: 5

Related Questions