Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

CSS module hover styles when inside another module

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?

like image 321
Spadar Shut Avatar asked Mar 21 '16 12:03

Spadar Shut


2 Answers

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 {...} 
like image 91
Cubed Eye Avatar answered Sep 21 '22 02:09

Cubed Eye


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.

like image 32
Spadar Shut Avatar answered Sep 22 '22 02:09

Spadar Shut