Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cascade styles in React CSS module

In my React app I had some messed up combination of inline JS styles and CSS classes. I decided to split up everything into CSS modules that I can use this way:

import styles from './ImageTextOption.module.css'

And use them like JS objects. However, now styles don't cascade from parent elements (that aren't defined in the same module). I had something like .selected .option-text, and even though I do have selected class outside, because option-text has changed into a unique name it doesn't match the option-text inside selected element. What is the correct approach to get it matching again, using CSS modules.

like image 989
Can Poyrazoğlu Avatar asked Sep 21 '26 10:09

Can Poyrazoğlu


1 Answers

I've run into the same challenge and have found it easier at times to pass styles as props to your child components. This is a good pattern if you are reusing the child component in different places.

Here is an example that accomplishes the very same.

Of course if the child component is specific to the parent component and is only used once, or if the parent-child combination is specific to each other, then maybe an approach would be for them to simply share the the css import at the parent level, then pass it down to child via className='

like image 100
EspressoBeans Avatar answered Sep 23 '26 06:09

EspressoBeans