Answer a question

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.

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;
   }
 }
Logo

React社区为您提供最前沿的新闻资讯和知识内容

更多推荐