I have a component that has its own style, e.g.
.prompt { color: red; }
It's declared as so:
import cn from 'classnames';
import styles from './styles.css';
const MyComponent = ({className}) => {
return (
<div className={cn(styles.prompt, className)}>
test
</div>
);
}
In my specific use case, the stylesheet for the className being passed in is actually defined and added to the head BEFORE the stylesheet from the module, so the module's css always overrides the style of the className being passed in. Something like:
Notice the background: yellow
from second class is being overridden by the background from the module's own class.
Other than using !important in the secondary class, how can I work around this?
To override a style, you have two options. Either you can pass a style object, or you can pass a function that will obtain props regarding the current internal state of the component, thus enabling you to modify styles dynamically depending on the component state, such as isError or isSelected .
If you love using Styled-Components or CSS modules, you have the freedom to use it with Material UI. In my opinion, this sort of flexibility is very important to widen the usage of a styling library. There are a few things you should keep in mind if you are combining JSS based styling with Material UI.
Based on Mr. Lister's response, I re-evaluated my existing knowledge of specificity and came up with the following solution in the higher level css:
// in app.scss
.offline.prompt {
color: red;
}
// in app.tsx
const classes = cn(Styles.offline, Styles.prompt);
return <OfflineApp className={classes}>...</OfflineApp>;
Essentially, I just tag the module markup with another sibling class to increase specificity and target the necessary properties using that. WAY better than abusing !important.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With