Can I override Material-UI with css modules in create-react-app v2?

Viewed 9918

For example I want to add margin-top to this button

import classes from 'button.module.css';
        <Button 
          type="submit"
          variant="contained"
          color="primary"
          fullWidth
          disabled={this.props.isLoading}
          className={classes.Button}
        >
          {this.props.isLoading ? <CircularProgress size={20}/> : 'SIGN IN'}
        </Button>

In button.module.css file

.Button {
  margin-top: 15px;
}

Is this possible to use this method instead of override like instruction in official material-ui page?

3 Answers

Simply use StylesProvider component with the injectFirst property:

import React from 'react'
import ReactDOM from 'react-dom'
import App from './App'
import { StylesProvider } from "@material-ui/core/styles" // <-- import this component, and wrap your App.

ReactDOM.render(
    <StylesProvider injectFirst>
        <App />
    </StylesProvider>,
    document.getElementById('root')
)

It's a problem of CSS specificity, in which your CSS is loaded before the Material UI's styles, and therefore is overridden by them. As stated in the docs, regarding the injectFirst property:

By default, the styles are injected last in the element of the page. As a result, they gain more specificity than any other style sheet. If you want to override Material-UI's styles, set this prop.

Yes, you can.

Use className like you normally you do with CRA.

This will explain how to use CSS modules. This is straightforward.

However, after doing the above-mentioned thing, I had an issue of my CSS getting overridden by MaterialUI CSS. So we need to change the order of Styleinjection.

This explains how you can do this.

Here is a sandbox with a working sample.

In my recent project i did things like

import './style.css';

where this is example content of style.css

.detailbox-paper {
  width: 90vw;
  margin: 20px auto 0px auto;
}

where i consumed it by using a className on the element like this <Paper className="detailbox-paper"> and it worked. One thing to keep in mind by this approach, is the css specificity you are then starting to fight with.

You can also use inline styles={{}} with the camelCase syntax for attributes. But, as far as i know, inline styles always will be set, exept there is the !important keyword.

Hopefully this could help you on your journey.

Related