How to style child components in React with CSS Modules How to style child components in React with CSS Modules reactjs reactjs

How to style child components in React with CSS Modules


There is multiple approach for this, with and without drawbacks.

Wrap each child in a div

This first one is to wrap each of your child components in a div and then add a class on it which then you can reference in your stylesheet:

return(    <div>        <div className={style.child}><ChildB /></div>        <div className={style.child}><Child /></div>        <div className={style.child}><Child /></div>    </div>);

Pass the className as props

You can pass the class name as props and then add this props to any tag you want in your Child component. On the other hand, you have to do this for every components that you would like to have a class.

return(    <div>        <ChildB className={style.child}/>        <Child className={style.child}/>        <Child className={style.child}/>    </div>);
//ChildComponent.jsImport Styles from 'ChildComponent.scss';...export default ({ className }) =>     <div className={`${Styles.child} ${className}`}></div>

Use the CSS child combinator

In your parent stylesheet, you can use the direct children selector > to select any direct children. You can also combine this operator with the star operator, but be careful with this one since it may slow the browser if used to frequently on a page

If we assume all your Child component is a div:

/* ParentComponent.scss */.parent > div {  }

Or if you don't how of what Child are made of

/* ParentComponent.scss */.parent > *{  }