Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Material UI css load order

I am having hard time understanding how I should structer my project. I am using react with material UI and css modules. Problem is that god knows why, all styling from MUI loads at the bottom of the header same as css module styling. After some research I found two solutions:

  1. Use !important inside css modules which is terrible.
  2. Changing the injection order https://material-ui.com/guides/interoperability/#css-modules

Problem with the second one is that it would be terrible tedieouse in a multi component project where every time you introduce a new component you have to load it manually as in the example. Am I missing something obvious? Do you have any ideas how to easier change the load order?

like image 781
Michał Korzeniowski Avatar asked Aug 13 '26 23:08

Michał Korzeniowski


2 Answers

According to the Material-UI documentation, you should add a <StylesProvider/> component, which wraps your component tree.

import { StylesProvider } from '@material-ui/core/styles';

<StylesProvider injectFirst>
  {/* Your component tree.
      Styled components can override Material-UI's styles. */}
</StylesProvider>

If injectFirst is set (and true of course), the Material UI style tags will be injected first in the head (less priority)

like image 94
bencergazda Avatar answered Aug 16 '26 17:08

bencergazda


I think you may be misunderstanding something in the example. There isn't anything you need to do on a per-component basis to change the load order. The steps are as follows:

1. In your index.html add a comment like <!-- jss-insertion-point --> into the head where you would like the jss CSS to be inserted.

2. In your index.js (or somewhere at or near the top of your rendering hierarchy) create the jss configuration to indicate the name of the insertion point comment:

import JssProvider from "react-jss/lib/JssProvider";
import { create } from "jss";
import { jssPreset } from "@material-ui/core/styles";

const jss = create({
  ...jssPreset(),
  // We define a custom insertion point that JSS will look for injecting the styles in the DOM.
  insertionPoint: "jss-insertion-point"
});

3. Wrap your top-level element in the JssProvider to put those configurations in play (no component-specific steps):

function App() {
  return (
    <JssProvider jss={jss}>
      <div className="App">
        <Button>Material-UI</Button>
        <Button className={styles.button}>CSS Modules</Button>
      </div>
    </JssProvider>
  );
}

I've created a CodeSandbox similar to the one pointed at by the Material-UI documentation except that this one uses the create-react-app starting point, so the dependencies are simpler.

Edit r5o1vw5po

like image 34
Ryan Cogswell Avatar answered Aug 16 '26 18:08

Ryan Cogswell