Any way to target classes with Material UI's createTheme?

Viewed 623

I know the basics with MUI's createTheme and changing component defaults like Typography, but how do I select classNames? In my situation, I want to only create themes for specific Typography/Grids in tandem with breakpoints, but there's no clear example of changing target components in the docs. Here's what I have so far:

  let theme = createTheme({
    typography: {
      fontFamily: "Inter, sans-serif",
      color: "#212b37",
      h5: {
        fontSize: 40,
      },
      body: {
        fontSize: 18,
      },
    },
    root: {
        sample_class: {
            fontSize: 40,
        }
    }
  });

I saw the docs mentioned root so I just winged it and added sample_class thinking that'll select the element with the same className.

1 Answers

Just for reference, I'm using MUI version ^5.0.0-rc.1.

Perhaps you can try something like this in createTheme:

Solution 1:

MuiTypography: {
  styleOverrides: {
    h6: ({ ownerState }) => (ownerState.className === "MyClass" ? { color: "red" } : {}),
  },
},

where "MyClass" is the name of the class you want to apply theme stylings to.

Solution 2:

This is cleaner.

MuiTypography: {
  styleOverrides: {
    h6: {
      '&.MyClass': { color: 'red' },
    },
  },
},

Then you can do this with your Typography element:

<Typography variant="h6" className="MyClass">Hello world</Typography>

If you have VS Code, you can Command+Click until you get to the TypographyClasses interface, which gives you a full list of typography classes to override.

Here are some links of ownerState which can help on component overriding:

This was also my solution for trying to style another component, such as the MuiAccordion, but I didn't want to override the existing variants since they had their own default styles.

Related