CSS-Modules with React.js

I would like to introduce react-css-modules with React.js.
CSS-Module is a concept for seamless mapping of class names to CSS modules inside of React components.


Installation

Install following libraries:

1
2
3
4
$ npm init -y
$ npm install --save react react-dom
$ npm install --save-dev webpack style-loader css-loader sass-loader node-sass extract-text-webpack-plugin
$ npm install --save-dev resolve-url resolve-url-loader babel-plugin-transform-decorators-legacy

Setup CSS loader

Add following codes to .babelrc:

1
2
3
{
"plugins": ["transform-decorators-legacy"]
}

Please add following codes in webpack.config.js:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
module: {
loaders: [
{
test: /\.css$/,
loaders: [
'style?sourceMap',
'css?modules&importLoaders=1&localIdentName=[path]___[name]__[local]___[hash:base64:5]'
]
},
{
test: /\.scss$/,
loaders: [
'style',
'css?modules&importLoaders=1&localIdentName=[path]___[name]__[local]___[hash:base64:5]',
'resolve-url',
'sass'
]
}
]
}

Usage

In the context of React, CSS Modules look like this:

1
2
3
4
5
6
7
8
9
10
11
12
/* css/table-custom-styles.scss */
.table {
width: 400px;
}
.row {
composes: row from './table.css';
}
.cell {
float: left; width: 154px; background: #eee; padding: 10px; margin: 10px 0 10px 10px;
}

In ES6 syntax, we can support CSS like this:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
// components/Table.jsx
import React from 'react';
import styles from '../css/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>;
}
}

ES7 decorators syntax is as follows:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
// components/Table.jsx
import React from 'react';
import CSSModules from 'react-css-modules';
import styles from './table.css';
@CSSModules(styles)
export default class extends React.Component {
render () {
return <div styleName='table'>
<div styleName='row'>
<div styleName='cell'>A0</div>
<div styleName='cell'>B0</div>
</div>
</div>;
}
}

Happy Hacking!

Special Thanks