No Programming, No Life
Jan 1, 2017 • 3 min read

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}>
            <div className={styles.row}>
                <div className={styles.cell}>A0</div>
                <div className={styles.cell}>B0</div>
            </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'>
            <div styleName='row'>
                <div styleName='cell'>A0</div>
                <div styleName='cell'>B0</div>
            </div>
        </div>;
    }
}

Happy Hacking!

Special Thanks