Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to nest classes in css modules and react?

I am trying to use CSS Modules in my React project. First part of the problem is that if I write nested css classes (using sass), I don't know if I can access the inner ones, since those seems to be compiled into unique classnames as well. Some code:

<div className={this.state.visible ? styles.header+" menu-visible" : styles.header}>     <div className="menu">         <a className="link">title</a>     </div> </div>     .header {        &.menu-visible {             .menu {                  display:block;             }         }     } 

I have a wrapping class that sometimes is "menu-visible" which changes attributes on all the children, is it bad practice to do it like this in React?

There is multiple classes inside the .header that are changed if the menu is visible, therefore it would be convinient to just change the wrapping class, can I reference the children in some way? So that the remain nested in scss?

EDIT

One solution that I can think of is to replace className="menu" with className={styles.header.menu} but that seemed not to work. The problem is that I would like .menu to change its attributes if its parent has the class menu-visible.

like image 363
rablentain Avatar asked Dec 01 '16 07:12

rablentain


People also ask

Can CSS classes be nested?

CSS Nested Classes: How To Write More Organized and Maintainable CSS. CSS nested classes are the way to write CSS classes within each other and hence, create more elevated CSS codes. Since nested classes allow you to group related classes, this leads to more organized code.

Does react support CSS modules?

We will use CSS modules in the context of React but they are not limited to just React. You can use the CSS modules with any module bundler like webpack or browserify or any other way which supports importing CSS files. An alternative to CSS modules in React to create local scope is to use styled components.


2 Answers

I solved it. I think that I just overdid it in my mind. Instead of writing styles.header.menu I could just write styles.menu, even if it was nested.

Example (React + JSX):

<div className={styles.header}>   <div className={styles.menu}>       Whatever   </div> </div>  .header {    .menu {       display: block;    }  } 
like image 113
rablentain Avatar answered Sep 22 '22 01:09

rablentain


An alternative solution which better preserves the nested classes and styling is to use the global scope :global on all the nested classes when using a preprocessor like sass or less.

.header {   :global {     .menu {       display: none;        &.menu-visible {         display:block;       }     }   } } 
<div className={styles.header}>   <div className="menu menu-visible">       Whatever   </div> </div> 
like image 37
Simon Watson Avatar answered Sep 24 '22 01:09

Simon Watson