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?
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:
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"; } 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 {...}
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With