material-ui

MUI Theme does not work for native elements


I am using themes in MaterialUI. If I have a theme like this :

export const myTheme = createTheme({
  typography: {
    h1: {
      color: '#D7101D',
      fontFamily: '"DeliveryCondensedBlack","Roboto","Arial"',
      fontSize: 160,
      letterSpacing: '-1.8px',
    },
  },
});

And I apply the theme like this in my APP then only the FIRST row has the theme applied.

createRoot(document.getElementById('root')!).render(
  <CacheProvider value={muiCache}>
    <ThemeProvider theme={myTheme}>
      <div>
        <Typography variant="h1">TEST1</Typography>
        <h1>TEST2</h1>
      </div>
    </ThemeProvider>

  </CacheProvider>
);

enter image description here

How can I apply the style to all my native HTML elements? (I cannot rewrite the elements into Typography elements because the legacy system is too large)


Solution

  • You can override raw/native HTML elements (h1, p, ul, etc.) via the MUI theme in at least MUI versions 5 - 7. You'll need to add the <CssBaseline /> component to the root of your app (if you're not already using it) and then pass the styleOverrides for your elements under the MuiCssBaseline property in the theme. For example:

    import * as React from "react";
    import { createTheme, ThemeProvider } from "@mui/material/styles";
    import { CssBaseline } from "@mui/material";
    
    const theme = createTheme({
      components: {
        MuiCssBaseline: {
          styleOverrides: {
            h1: {
              color: "#D7101D",
              fontFamily: '"DeliveryCondensedBlack","Roboto","Arial"',
              fontSize: 160,
              letterSpacing: "-1.8px",
            },
          },
        },
      },
    });
    
    export default function DefaultProps() {
      return (
        <ThemeProvider theme={theme}>
          <CssBaseline />
          <h1>Test 2</h1>
        </ThemeProvider>
      );
    }
    

    Result: enter image description here

    Working Codesandbox: https://codesandbox.io/p/sandbox/zealous-mcclintock-qchq6k?file=%2Fsrc%2FDemo.tsx%3A18%2C4