Search code examples
reactjsreact-css-modules

Applying style of multiple CSS classes using React CSS Modules


I have a React component that dynamically applies a CSS style class using the onClick listener. This works and when I view the generated html in the browser inspector I can see my desired output.

<div class="RecipeSection_recipe-section__Asce8 active">
<h2>Ingredients</h2>
</div>

However the styling I have defined in my React CSS Module is not applied

.recipe-section.active h2 {
  text-align: center;
  color: red;
}

When I remove the .active class I can see the red styling applied.

I guess because the React CSS Module adds a hash to the name it is impacting the class concatenation, but I am not sure if there is a way to resolve this within the React CSS module?


Solution

  • The reason the style wasn't being applied is because I had supplied the css 'active' class as a string value rather than as a reference from the imported CSS module:

    import classes from "./RecipeSection.module.css";
    

    Then I could supply the reference:

    ${classes.active}
    

    The real clue was that in the initial generated html, my active class had not been allocated a hash as the recipe-section class had

    <div class="RecipeSection_recipe-section__Asce8 active">