Home > Enterprise >  Material UI v5 styles applied to class does'nt apply?
Material UI v5 styles applied to class does'nt apply?

Time:02-12

I am trying to style the MUI slider,so I decided to style it using the className prop. But the style applied to the main class does'nt get applied,while rest other styles like 'hover' state get applied. If I remove all the classes and just style it using SX prop,everything works fine. But I want to keep the styles seperate into an external css file.

Below is my code :

App.css

.container{
  margin-left: 30%;
  margin-top: 20%;

}

/* This does'nt get applied */
.slider {
  color: #ff0000;
  width: 300px;
}


.slider:hover {
  color: #2e8b57;
}

.slider > .MuiSlider-thumb {
  border-radius: 1px;
}

App.js

import "./App.css"
import * as React from 'react';
import Slider from '@mui/material/Slider';

export default function App() {
  return (
    <div className="container">
      <Slider className="slider"  defaultValue={30} />
    </div>
  );
}

CodePudding user response:

The problem is with Material UI style injection order. The custom styles do apply, but Mui styles are injected before the custom style so they doesn't have effect in this case.

This guide explain how to change the injection order:

https://mui.com/guides/interoperability/#css-injection-order

CodePudding user response:

I don't know if it is required, but I use css modules and material-ui. You can rename your css file to

App.module.css

then import like so

import styles from "./App.module.css"

you can then use it like

<Slider className={styles.slider}  defaultValue={30} />

In Nextjs you can throw everything in styles.css to make it global, but I don't know if that is also for react as well.

  • Related