Search code examples
reactjsreact-css-modules

Overwrite styles of a component inside another in react


I have a component with its own styles:

import styles from './componentA.module.scss';

componentA.module.scss:

.A { color: green;
     background: white;
     font-size: 1rem;}

ComponentA.js

....
return(
   <div className={styles.A}>{props.children}</div>
)

I have a ComponentB.js. In this component B I need the component A, but I need to overwrite the style color.

ComponentB.js

...
import ComponentA from './../componentA';
import styles from 'componentB.module.scss';
...
return(
<ComponentA />
)

but I want in the component B overwrite the color to the class .A. I tried in componentB.module.scss to do it and it doesn't change.

componentB.module.scss

.A {
 color: red !important;
}

and it doesn't work I want to be able to overwrite the styles depending on the component that is wrapped. How can I do it? Thanks.


Solution

  • You have to pass Component A styles by the props and then apply to the wrapper div

    const ComponentA = (props) => {
    
      return(
        <div className={styles.A} styles={props.cssStyles}>{props.children}</div>
        )
      }
    

    And then

    import ComponentA from './../componentA';
    import styles from 'componentB.module.scss';
    ...
    return(
    <ComponentA cssStyles={{color: "red"}} />
    )
    

    You can also pass classnames as props and then merge default classnames and props classnames by this package https://www.npmjs.com/package/classnames