26

In a React/Webpack app with CSS modules I have a module .card in its own .scss file and another module named .stat which is a content to be shown in the .card.

What I need to achieve the following, but int the 'css-modules' way:

.card:hover .stat {
    color: #000;
}

If I @import .card inside the .stat module, all of the .card css is dumped into the .stat output, but I only want to be able to use the correct class name for the .card.

What's the correct way to solve the problem?

Spadar Shut
  • 15,111
  • 5
  • 47
  • 54

2 Answers2

8

We had a similar issue in our use of CSS modules. I open an issue https://github.com/css-modules/css-modules/issues/102 and it was suggested to me that I should do either one of the following:

  1. Clone the component and add a new className attribute to it and compose the new class with the old class:

    // Card.js
    React.cloneElement(component, {
      className: styles.card, 
    });
    
    // styles.cssmodule 
    .card {
      composes: card from "...card.cssmodule"; 
    }
    
  2. Wrap the component in another element and add the classname to this:

    <div className={styles.card}><MyComponent /></div>
    

I didn't like either of these approaches and I'd like to use the strength of css-modules which is the modules part. So we have a fork of the css-loader which allows you to use :ref() to reference imported classes:

:import('...card.cssmodule`){
  importedCard: card;
}

:ref(.importedCard):hover .stat {...}
ThomasThiebaud
  • 11,331
  • 6
  • 54
  • 77
Cubed Eye
  • 5,581
  • 4
  • 48
  • 64
  • 2
    Still looks like this is a workaround, not a true solution (which in turn seems to be non-existent as of now) – Spadar Shut Mar 30 '16 at 10:57
7

As a workaround React toolbox guys use an approach to add a data-react-toolbox="component-name" or data-role="somerole" attribute to every component and target the attribute instead of classes where necessary for such situations.

Spadar Shut
  • 15,111
  • 5
  • 47
  • 54