cssreactjscss-modulesreact-css-modules

CSS Modules & ReactJS: Parent and child CSS classes in different components


So I am building a react application and have a quick question. If I have two separate components: and with CSS classes navigation.css and navigationLogo.css respectively. In navigation.css I have a class named .main and in navigationLogo.css I want to have a class like so:

.main .main_in_logo {
 color: red;
}

But with CSS Modules I am unable to do this, any ideas on a work around?


Solution

  • The child component should not have a css rule that is dependent upon the parent css classname.

    the child should just be:

    .main_in_logo { color: red; }
    

    If you need to define styles that involve both parent and child, then the easiest way is to define the styles completely in the parent:

    /* navigation.css */
    .main .main_in_logo {
       color: red;
    }
    

    Then have the parent pass the css class to the child and tell the child to use it:

    // Navigation.js
    <NavigationLogo className={navigationCss.main_in_logo} />
    
    // NavigationLogo.js
    <div className={"foo " + this.props.className}>stuff</div>