MUI v5 theming with emotion/mui

Viewed 3956

I've upgraded MUI from v4 to v5. However, I'm now having difficulties understanding how the theming works with the different theming solutions available. I don't really understand where to use the MUI theming/styling components and when to use the emotion ones.

In new components, I'm using the sx prop to apply styling, however I have quite a lot of components still using the createStyles/useStyles functions.

I currently have the following setup:

import {
  ThemeProvider as MuiThemeProvider,
  Theme,
  StyledEngineProvider,
  createTheme,
} from "@mui/material/styles";
import { ThemeProvider } from "@emotion/react";

declare module "@mui/material/styles" {
  interface Theme {
    mycompany: {
      primary: string;
    };
  }
  // allow configuration using `createTheme`
  interface ThemeOptions {
    mycompany: {
      primary: string;
    };
  }
}

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

const theme = createTheme({
  mycompany: {
    primary: "#003366",
  },
});

const App = () => {
  return (
    <StyledEngineProvider injectFirst>
      <MuiThemeProvider theme={theme}>
        <ThemeProvider theme={theme}>
          <Router>
            ...
          </Router>
        </ThemeProvider>
      </MuiThemeProvider>
    </StyledEngineProvider>

How can I now use the theme.mycompany.primary value? I've tried it like this:

import { useTheme } from "@emotion/react";

const MyComponent = () => {
    const theme = useTheme();

    return (
      <Box sx={{backgroundColor: theme.mycompany.primary}}>
        ...
      </Box>

Are there any examples of projects using the new styling solution with typescript across multiple components in different files?

1 Answers

From the docs, useTheme should be imported from @mui/material/styles.

If you use sx prop, you should put your custom color code in the palette like this:

const theme = createTheme({
  palette: {
    mycompany: {
      primary: "#003366"
    }
  },
});

And reference the color in your component:

<Box sx={{ width: 30, height: 30, bgcolor: "mycompany.primary" }} />

If you're using styled you can add a callback where the theme is a property of the first param:

const MyComponent = styled(Box)(({ theme }) => {
  return {
    backgroundColor: theme.palette.mycompany.primary,
    width: 30,
    height: 30
  };
});

Live Demo

Codesandbox Demo

Related