EDIT: Here’s stackblitz for example app
EDIT 2: See my answer for simple solution
I have a React component that shows an alert component with the scss.
export function MyComponent() {
return (
<div className={styles.alert}>
<ModusAlert message={'Some message'}></ModusAlert>
</div>
);
}
MyComponent.module.css
.alert {
width: 390px;
margin-top: 182px;
margin-bottom: 22px;
}
Now I need to change color and background-color among other things. When I look at the style in DevTools for the label inside the alert there’s a style below.
Style in DevTools:
div.alert .message {
font-size: 0.875rem;
font-weight: 700;
}
Editing that style in DevTools to the style below changes the appearance of the web page.
Edited style in DevTools (changes appearance):
div.alert .message {
font-size: 0.875rem;
font-weight: 700;
color: white;
}
However, if I add that style from DevTools to my component’s CSS, it doesn’t work.
Edited style from DevTools added to CSS (does NOT change appearance):
div.alert .message {
font-size: 0.875rem;
font-weight: 700;
color: white;
}
So how this should be done? Below is the element style for div that contains the message of alert:
4
Answers
In this case the easiest way to override the alert color seems to be setting the css custom properties / css variables used in the 3rd party library. The appropriate variables can be found from the component style file. So changing the existing style in MyComponent.module.css:
you can override a css with make a selector more precise than the one you want override, or with the key-word "important".
(if I correctly understand the problem you ask)
Can you please check the below solution? Hope it will work for you.
You have written CSS code in
MyComponent.module.css
, which is intended to work only in the elements of the same component. However, you have used theModusAlert
library for the alert, which is another component.To resolve this, you need to move your custom CSS related to
ModusAlert
into the global CSS/SCSS file such asglobal.css
orglobal.scss
, rather than any other*.module.css
file.First of all, you must know about
Shadow DOM
and its usage. This Modus library I think was developed by using Shadow DOM to avoid CSS conflict and you are so lucky because its Shadow DOM is open and by using JS PATH it would be possible to have some styles modification. So, if you want to modify the styles you must use the following trick:For more information have a look at this post
— Update (based on the reproduction link):
You need to use an
useEffect
to implement your change, pay attention the following code: