Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

CSS Modules, React and Overriding CSS Classes

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

like image 787
Joe Bruno Avatar asked Feb 04 '16 19:02

Joe Bruno


People also ask

Can you override a CSS class?

To override the CSS properties of a class using another class, we can use the ! important directive. In CSS, ! important means “this is important”, and the property:value pair that has this directive is always applied even if the other element has higher specificity.

Does React support CSS modules?

We will use CSS modules in the context of React but they are not limited to just React. You can use the CSS modules with any module bundler like webpack or browserify or any other way which supports importing CSS files. An alternative to CSS modules in React to create local scope is to use styled components.


1 Answers

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

like image 181
alechill Avatar answered Sep 22 '22 23:09

alechill