CSS Modules, React and Overriding CSS Classes

Joe Bruno picture Joe Bruno · Feb 4, 2016 · Viewed 42.2k times · Source

I am using a React component library (React Toolbox), which is outputting this class in their Tab component using CSS Modules and Webpack: label___1nGy active___1Jur tab___Le7N The tab is a className prop I am passing down. The label and active classes are coming from the library. I want to apply a different set of styles on active, something like .tab.active where tab is referring to the styles I have created and active matches the generated selector the library has created but cannot figure out how to do this with css-modules. I need to override this dynamically selector: .label___1nGy.active___1Jur.

Browser

[CSS]]2 [React]3

Answer

alechill picture alechill · Jan 11, 2017

Old post but still relevant, so adding an answer to help those with similar issue

While not inherently possible in CSS modules alone, the author of the react-toolbox library has actually solved this particular problem very nicely

Read their github docs which are more in depth on the subject at https://github.com/react-toolbox/react-toolbox#customizing-components

A list of the themeable classes for a particular component is given on the component demo page on their site too

In your case as well as passing a className for tab, you would also create a theme with classes that overrides that desired parts of the default theme and pass that as the theme prop. For example something alog the lines of...

MyComponentWithTabs.css

.tab {
  color: white;
}

MyTabTheme.css

.active {
  color: hotpink;
}

MyComponentWithTabs.js

import styles from './MyComponentWithTabs.css'
import tabTheme from './MyTabTheme.css'

// blah blah...

return <Tab key={index} className={styles.tab} theme={tabTheme} />

Under the surface this uses a decorator they have abstracted into separate library react-css-themr, I recommend giving that a read too as it explains how the defaults are composed with your overrides in much greater depth, including the different merging strategies they use