React CSS Modules implement automatic mapping of CSS modules. Every CSS class is assigned a local-scoped identifier with a global unique name. CSS Modules enable a modular and reusable CSS!
⚠️⚠️⚠️ DEPRECATION NOTICE ⚠️⚠️⚠️
If you are considering to use react-css-modules, evaluate if babel-plugin-react-css-modules covers your use case.
babel-plugin-react-css-modules is a lightweight alternative of react-css-modules.
babel-plugin-react-css-modules is not a drop-in replacement and does not cover all the use cases of react-css-modules.
However, it has a lot smaller performance overhead (0-10% vs +50%; see Performance) and a lot smaller size footprint (less than 2kb vs +17kb).
CSS Modules are awesome. If you are not familiar with CSS Modules, it is a concept of using a module bundler such as webpack to load CSS scoped to a particular document. CSS module loader will generate a unique name for each CSS class at the time of loading the CSS document (Interoperable CSS to be precise). To see CSS Modules in practice, webpack-demo.
In the context of React, CSS Modules look like this:
import React from 'react';import styles from './table.css';export default class Table extends React.Component { render () { return <div className={styles.table}> <div className={styles.row}> <div className={styles.cell}>A0</div> <div className={styles.cell}>B0</div> </div> </div>; }}
Rendering the component will produce a markup similar to:
and a corresponding CSS file that matches those CSS classes.
Awesome!
webpack css-loader
CSS Modules is a specification that can be implemented in multiple ways. react-css-modules leverages the existing CSS Modules implementation webpack css-loader.
What's the Problem?
webpack css-loader itself has several disadvantages:
You have to use camelCase CSS class names.
You have to use styles object whenever constructing a className.
Mixing CSS Modules and global CSS classes is cumbersome.
Reference to an undefined CSS Module resolves to undefined without a warning.
React CSS Modules component automates loading of CSS Modules using styleName property, e.g.
You are warned when styleName refers to an undefined CSS Module (handleNotFoundStyleName option).
You can enforce use of a single CSS module per ReactElement (allowMultiple option).
The Implementation
react-css-modules extends render method of the target component. It will use the value of styleName to look for CSS Modules in the associated styles object and will append the matching unique CSS class names to the ReactElementclassName property value.
In this example, CSSModules is used to decorate Table component using ./table.css CSS Modules. When Table component is rendered, it will use the properties of the styles object to construct className values.
Using styles property you can overwrite the default component styles object, e.g.
import customStyles from './table-custom-styles.css';<Table styles={customStyles} />;
styleName cannot be used to define styles of a ReactElement that will be generated by another component, e.g.
import React from 'react';import CSSModules from 'react-css-modules';import List from './List';import styles from './table.css';class CustomList extends React.Component { render () { let itemTemplate; itemTemplate = (name) => { return <li styleName='item-template'>{name}</li>; }; return <List itemTemplate={itemTemplate} />; }}export default CSSModules(CustomList, styles);
The above example will not work. CSSModules is used to decorate CustomList component. However, it is the List component that will render itemTemplate.
For that purpose, the decorated component inherits styles property that you can use just as a regular CSS Modules object. The earlier example can be therefore rewritten to:
import React from 'react';import CSSModules from 'react-css-modules';import List from './List';import styles from './table.css';class CustomList extends React.Component { render () { let itemTemplate; itemTemplate = (name) => { return <li className={this.props.styles['item-template']}>{name}</li>; }; return <List itemTemplate={itemTemplate} />; }}export default CSSModules(CustomList, styles);
You can use styleName property within the child component if you decorate the child component using CSSModules before passing it to the rendering component, e.g.
import React from 'react';import CSSModules from 'react-css-modules';import List from './List';import styles from './table.css';class CustomList extends React.Component { render () { let itemTemplate; itemTemplate = (name) => { return <li styleName='item-template'>{name}</li>; }; itemTemplate = CSSModules(itemTemplate, this.props.styles); return <List itemTemplate={itemTemplate} />; }}export default CSSModules(CustomList, styles);
Options are supplied as the third parameter to the CSSModules function.
CSSModules(Component, styles, options);
or as a second parameter to the decorator:
@CSSModules(styles, options);
allowMultiple
Default: false.
Allows multiple CSS Module names.
When false, the following will cause an error:
<div styleName='foo bar' />
handleNotFoundStyleName
Default: throw.
Defines the desired action when styleName cannot be mapped to an existing CSS Module.
Available options:
throw throws an error
log logs a warning using console.warn
ignore silently ignores the missing style name
SASS, SCSS, LESS and other CSS Preprocessors
Interoperable CSS is compatible with the CSS preprocessors. To use a preprocessor, all you need to do is add the preprocessor to the chain of loaders, e.g. in the case of webpack it is as simple as installing sass-loader and adding !sass to the end of the style-loader loader query (loaders are processed from right to left):
CSS Modules promote composition pattern, i.e. every CSS Module that is used in a component should define all properties required to describe an element, e.g.
This pattern emerged with the advent of OOCSS. The biggest disadvantage of this implementation is that you will need to change HTML almost every time you want to change the style.
Class Composition Using CSS Preprocessors
This section of the document is included as a learning exercise to broaden the understanding about the origin of Class Composition. CSS Modules support a native method of composing CSS Modules using composes keyword. CSS Preprocessor is not required.
CSS Modules does not restrict you from using global CSS.
:global .foo {}
However, use global CSS with caution. With CSS Modules, there are only a handful of valid use cases for global CSS (e.g. normalization).
Multiple CSS Modules
Avoid using multiple CSS Modules to describe a single element. Read about Class Composition.
That said, if you require to use multiple CSS Modules to describe an element, enable the allowMultiple option. When multiple CSS Modules are used to describe an element, react-css-modules will append a unique class name for every CSS Module it matches in the styleName declaration, e.g.
.button {}.active {}
<div styleName='button active'></div>
This will map both Interoperable CSS CSS classes to the target element.