3

In Material-UI v4, you were able to use the Mui* class names on any elements and have the styles of those classes take effect, as long as the MUI components that use those classes are incorporated somewhere (thereby injecting the styles into the page CSS). For instance, you could add class names like className="MuiTypography-root MuiLink-root MuiLink-underlineHover MuiTypography-colorPrimary" to some HTML element to match all of the styles of a MUI <Link />, like in this codepen. In MUI v5, this has no effect, as can be seen in this identical codepen using MUI v5, despite the fact that the class names are still being used on the MUI <Link /> (just not to apply CSS).

Applying MUI component styles to non-MUI components is important for a few different use-cases, where you need to apply styles to APIs that do not support supplying React components directly. For instance:

  1. When using react-router-dom's NavLink component with its activeClassName prop. In this case, the base component is styled a certain way, and you apply further classes (not props) to modify its styles when the NavLink is the "active" route. In MUI v4, you'd be able to use classes like activeClassName="Mui-selected" (for components that have a selected state), or MuiButton-outlinedPrimary to change a button variant via only classes.

  2. When using external APIs that deal with raw HTML elements, like rich-text editors (Tiptap, Draft.js, etc). It's useful to be able to pass MUI class names directly here so that you can style the rich-text elements to match MUI styles (like the link element in the above codepens).

The only way I can determine how to do this in MUI v5 is to use the deprecated makeStyles and create classes that duplicate all of the MUI styles manually. e.g. duplicate all of the CSS of Mui-Link-root within my own makeStyles call, then use the useStyles() generated class to apply the CSS. This would lead to significant duplication of MUI code and isn't a sustainable or even straightforward option. It would be simple in situations where you can use just the theme, like myBody1: {...theme.typography.body1}, but it's unclear how to do this for other components without copy-pasting from the generated CSS or MUI source.


This is related to this other question Apply MUI styles to non-MUI markup elements, but slightly different in scope, as I would like to reuse MUI's styles via class names I can apply to other elements (whereas that question would like to do so without using class names at all).

Steven D.
  • 493
  • 4
  • 12

0 Answers0