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:

$ 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:

{
"plugins": ["transform-decorators-legacy"]
}

Please add following codes in webpack.config.js:

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:

/* 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:

// 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}>

A0

B0

div>
div>;
}
}

ES7 decorators syntax is as follows:

// 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'>

A0

B0

div>
div>;
}
}

Happy Hacking!

šŸ—½ Special Thanks

šŸ–„ Recommended VPS Service

VULTR provides high performance cloud compute environment for you. Vultr has 15 data-centers strategically placed around the globe, you can use a VPS with 512 MB memory for just $ 2.5 / month ($ 0.004 / hour). In addition, Vultr is up to 4 times faster than the competition, so please check it => Check Benchmark Results!!