• Stars
    star
    5,232
  • Rank 7,910 (Top 0.2 %)
  • Language
    JavaScript
  • License
    Other
  • Created about 9 years ago
  • Updated about 5 years ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

Seamless mapping of class names to CSS modules inside of React components.

React CSS Modules

GitSpo Mentions Travis build status NPM version js-canonical-style

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).

It is easy to get started! See the demo https://github.com/gajus/babel-plugin-react-css-modules/tree/master/demo

CSS Modules

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:

<div class="table__table___32osj">
    <div class="table__row___2w27N">
        <div class="table__cell___1oVw5">A0</div>
        <div class="table__cell___1oVw5">B0</div>
    </div>
</div>

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.

import React from 'react';
import CSSModules from 'react-css-modules';
import styles from './table.css';

class Table extends React.Component {
    render () {
        return <div styleName='table'>
            <div styleName='row'>
                <div styleName='cell'>A0</div>
                <div styleName='cell'>B0</div>
            </div>
        </div>;
    }
}

export default CSSModules(Table, styles);

Using react-css-modules:

  • You are not forced to use the camelCase naming convention.
  • You do not need to refer to the styles object every time you use a CSS Module.
  • There is clear distinction between global CSS and CSS Modules, e.g.
<div className='global-css' styleName='local-module'></div>
  • 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 ReactElement className property value.

Awesome!

Usage

Setup consists of:

Module Bundler

webpack

Development

In development environment, you want to Enable Sourcemaps and webpack Hot Module Replacement (HMR). style-loader already supports HMR. Therefore, Hot Module Replacement will work out of the box.

Setup:

{
    test: /\.css$/,
    loaders: [
        'style-loader?sourceMap',
        'css-loader?modules&importLoaders=1&localIdentName=[path]___[name]__[local]___[hash:base64:5]'
    ]
}
Production

In production environment, you want to extract chunks of CSS into a single stylesheet file.

Advantages:

  • Fewer style tags (older IE has a limit)
  • CSS SourceMap (with devtool: "source-map" and css-loader?sourceMap)
  • CSS requested in parallel
  • CSS cached separate
  • Faster runtime (less code and DOM operations)

Caveats:

  • Additional HTTP request
  • Longer compilation time
  • More complex configuration
  • No runtime public path modification
  • No Hot Module Replacement

– extract-text-webpack-plugin

Setup:

  • Install style-loader.

  • Install css-loader.

  • Use extract-text-webpack-plugin to extract chunks of CSS into a single stylesheet.

  • Setup /\.css$/ loader:

    • ExtractTextPlugin v1x:

      {
        test: /\.css$/,
        loader: ExtractTextPlugin.extract('style', 'css?modules&importLoaders=1&localIdentName=[name]__[local]___[hash:base64:5]')
      }
    • ExtractTextPlugin v2x:

      {
        test: /\.css$/,
        use: ExtractTextPlugin.extract({
            fallback: 'style-loader',
            use: 'css-loader?modules,localIdentName="[name]-[local]-[hash:base64:6]"'
        }),
      }
  • Setup extract-text-webpack-plugin plugin:

    • ExtractTextPlugin v1x:

      new ExtractTextPlugin('app.css', {
          allChunks: true
      })
    • ExtractTextPlugin v2x:

      new ExtractTextPlugin({
        filename: 'app.css',
        allChunks: true
      })

Refer to webpack-demo or react-css-modules-examples for an example of a complete setup.

Browserify

Refer to css-modulesify.

Extending Component Styles

Use styles property to overwrite the default component styles.

Explanation using Table component:

import React from 'react';
import CSSModules from 'react-css-modules';
import styles from './table.css';

class Table extends React.Component {
    render () {
        return <div styleName='table'>
            <div styleName='row'>
                <div styleName='cell'>A0</div>
                <div styleName='cell'>B0</div>
            </div>
        </div>;
    }
}

export default CSSModules(Table, styles);

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

Interoperable CSS can extend other ICSS. Use this feature to extend default styles, e.g.

/* table-custom-styles.css */
.table {
    composes: table from './table.css';
}

.row {
    composes: row from './table.css';
}

/* .cell {
    composes: cell from './table.css';
} */

.table {
    width: 400px;
}

.cell {
    float: left; width: 154px; background: #eee; padding: 10px; margin: 10px 0 10px 10px;
}

In this example, table-custom-styles.css selectively extends table.css (the default styles of Table component).

Refer to the UsingStylesProperty example for an example of a working implementation.

styles Property

Decorated components inherit styles property that describes the mapping between CSS modules and CSS classes.

class extends React.Component {
    render () {
        <div>
            <p styleName='foo'></p>
            <p className={this.props.styles.foo}></p>
        </div>;
    }
}

In the above example, styleName='foo' and className={this.props.styles.foo} are equivalent.

styles property is designed to enable component decoration of Loops and Child Components.

Loops and Child Components

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);

Decorator

/**
 * @typedef CSSModules~Options
 * @see {@link https://github.com/gajus/react-css-modules#options}
 * @property {Boolean} allowMultiple
 * @property {String} handleNotFoundStyleName
 */

/**
 * @param {Function} Component
 * @param {Object} defaultStyles CSS Modules class map.
 * @param {CSSModules~Options} options
 * @return {Function}
 */

You need to decorate your component using react-css-modules, e.g.

import React from 'react';
import CSSModules from 'react-css-modules';
import styles from './table.css';

class Table extends React.Component {
    render () {
        return <div styleName='table'>
            <div styleName='row'>
                <div styleName='cell'>A0</div>
                <div styleName='cell'>B0</div>
            </div>
        </div>;
    }
}

export default CSSModules(Table, styles);

Thats it!

As the name implies, react-css-modules is compatible with the ES7 decorators syntax:

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

Awesome!

Refer to the react-css-modules-examples repository for an example of webpack setup.

Options

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

{
    test: /\.scss$/,
    loaders: [
        'style',
        'css?modules&importLoaders=1&localIdentName=[path]___[name]__[local]___[hash:base64:5]',
        'resolve-url',
        'sass'
    ]
}

Enable Sourcemaps

To enable CSS Source maps, add sourceMap parameter to the css-loader and to the sass-loader:

{
    test: /\.scss$/,
    loaders: [
        'style?sourceMap',
        'css?modules&importLoaders=1&localIdentName=[path]___[name]__[local]___[hash:base64:5]',
        'resolve-url',
        'sass?sourceMap'
    ]
}

Class Composition

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.

.box {
    width: 100px;
    height: 100px;
}

.empty {
    composes: box;

    background: #4CAF50;
}

.full {
    composes: box;

    background: #F44336;
}

Composition promotes better separation of markup and style using semantics that would be hard to achieve without CSS Modules.

Because CSS Module names are local, it is perfectly fine to use generic style names such as "empty" or "full", without "box-" prefix.

To learn more about composing CSS rules, I suggest reading Glen Maddern article about CSS Modules and the official spec of the CSS Modules.

What Problems does Class Composition Solve?

Consider the same example in CSS and HTML:

.box {
    width: 100px;
    height: 100px;
}

.box-empty {
    background: #4CAF50;
}

.box-full {
    background: #F44336;
}
<div class='box box-empty'></div>

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.

You can write compositions in SCSS using @extend keyword and using Mixin Directives, e.g.

Using @extend:

%box {
    width: 100px;
    height: 100px;
}

.box-empty {
    @extend %box;

    background: #4CAF50;
}

.box-full {
    @extend %box;

    background: #F44336;
}

This translates to:

.box-empty,
.box-full {
    width: 100px;
    height: 100px;
}

.box-empty {
    background: #4CAF50;
}

.box-full {
    background: #F44336;
}

Using mixins:

@mixin box {
    width: 100px;
    height: 100px;
}

.box-empty {
    @include box;

    background: #4CAF50;
}

.box-full {
    @include box;

    background: #F44336;
}

This translates to:

.box-empty {
    width: 100px;
    height: 100px;
    background: #4CAF50;
}

.box-full {
    width: 100px;
    height: 100px;
    background: #F44336;
}

Global CSS

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.

More Repositories

1

slonik

A Node.js PostgreSQL client with runtime and build time type safety, and composable SQL.
TypeScript
4,550
star
2

swing

A swipeable cards interface. The swipe-left/swipe-right for yes/no input. As seen in apps like Jelly and Tinder.
JavaScript
2,618
star
3

babel-plugin-react-css-modules

Transforms styleName to className using compile time CSS module resolution.
JavaScript
2,044
star
4

redux-immutable

redux-immutable is used to create an equivalent function of Redux combineReducers that works with Immutable.js state.
TypeScript
1,880
star
5

eslint-plugin-flowtype

Flow type linting rules for ESLint.
JavaScript
1,078
star
6

roarr

JSON logger for Node.js and browser.
TypeScript
1,062
star
7

prepack-webpack-plugin

A webpack plugin for prepack.
JavaScript
1,039
star
8

eslint-plugin-jsdoc

JSDoc specific linting rules for ESLint.
JavaScript
1,024
star
9

turbowatch

Extremely fast file change detector and task orchestrator for Node.js.
TypeScript
938
star
10

table

Formats data into a string table.
TypeScript
897
star
11

usus

Webpage pre-rendering service. ⚡️
JavaScript
805
star
12

flow-runtime

A runtime type system for JavaScript with full Flow compatibility.
JavaScript
802
star
13

surgeon

Declarative DOM extraction expression evaluator. 👨‍⚕️
JavaScript
693
star
14

liqe

Lightweight and performant Lucene-like parser, serializer and search engine.
TypeScript
636
star
15

eslint-config-canonical

The most comprehensive ES code style guide.
JavaScript
536
star
16

write-file-webpack-plugin

Forces webpack-dev-server to write bundle files to the file system.
JavaScript
528
star
17

lightship

Abstracts readiness, liveness and startup checks and graceful shutdown of Node.js services running in Kubernetes.
TypeScript
518
star
18

gitdown

GitHub markdown preprocessor.
JavaScript
445
star
19

xhprof.io

GUI to analyze the profiling data collected using XHProf – A Hierarchical Profiler for PHP.
PHP
429
star
20

contents

Table of contents generator.
JavaScript
416
star
21

brim

View (minimal-ui) manager for iOS 8.
JavaScript
391
star
22

global-agent

Global HTTP/HTTPS proxy agent configurable using environment variables.
TypeScript
360
star
23

youtube-player

YouTube iframe API abstraction.
JavaScript
340
star
24

react-aux

A self-eradicating component for rendering multiple elements.
JavaScript
329
star
25

http-terminator

Gracefully terminates HTTP(S) server.
TypeScript
324
star
26

isomorphic-webpack

Abstracts universal consumption of application code base using webpack.
JavaScript
291
star
27

scream

Dynamic viewport management for mobile. Manage viewport in different states of device orientation. Scale document to fit viewport. Calculate the dimensions of the "minimal" iOS 8 view relative to your viewport width.
JavaScript
289
star
28

graphql-deduplicator

A GraphQL response deduplicator. Removes duplicate entities from the GraphQL response.
JavaScript
279
star
29

create-index

Creates ES6 ./index.js file in target directories that imports and exports all sibling files and directories.
JavaScript
279
star
30

gajus.com-blog

The contents of the http://gajus.com/blog/.
JavaScript
226
star
31

wholly

jQuery plugin used to select the entire table row and column in response to mouseenter and mouseleave events. Wholly supports table layouts that utilize colspan and rowspan.
JavaScript
204
star
32

puppeteer-proxy

Proxies Puppeteer Page requests.
JavaScript
203
star
33

canonical-reducer-composition

Spec for Canonical Reducer Composition design pattern.
188
star
34

angular-swing

AngularJS directive for Swing: A swipeable cards interface. The swipe-left/swipe-right for yes/no input. As seen in apps like Jelly and Tinder, and many others.
JavaScript
183
star
35

dindent

HTML indentation library for development and testing.
PHP
177
star
36

babel-plugin-graphql-tag

Compiles GraphQL tagged template strings using graphql-tag.
JavaScript
172
star
37

eslint-plugin-canonical

ESLint rules for Canonical ruleset.
TypeScript
121
star
38

vlad

Input validation library promoting succinct syntax with extendable validators and multilingual support.
PHP
104
star
39

babel-plugin-log-deprecated

Adds a console.warn statement to the functions annotated with @deprecated tag.
JavaScript
103
star
40

redux-immutable-examples

A complete application showing use of redux-immutable.
JavaScript
103
star
41

babel-preset-es2015-webpack

Babel preset for all es2015 plugins except babel-plugin-transform-es2015-modules-commonjs.
JavaScript
97
star
42

scalpel

A CSS selector parser.
JavaScript
95
star
43

eslint-plugin-sql

SQL linting rules for ESLint.
TypeScript
93
star
44

graphql-lazyloader

GraphQL directive that adds Object-level data resolvers.
TypeScript
89
star
45

pg-formatter

A PostgreSQL SQL syntax beautifier.
TypeScript
80
star
46

orientationchangeend

The orientationchangeend event is fired when the orientation of the device has changed and the associated rotation animation has been complete.
JavaScript
78
star
47

bugger

Bugger is a collection of functions for debugging PHP code.
CSS
77
star
48

planton

Database-agnostic task scheduler.
TypeScript
77
star
49

dora

Input generation library for value resolution, data persistence, templates, CSRF and protection from XSS.
CSS
73
star
50

react-css-modules-examples

Usage examples for react-css-modules.
JavaScript
72
star
51

format-graphql

Formats GraphQL schema definition language (SDL) document.
JavaScript
71
star
52

to-string-loader

to-string loader for webpack
JavaScript
64
star
53

extract-email-address

Extracts email address from an arbitrary text input.
TypeScript
62
star
54

interdependent-interactive-histograms

This is a helper function that utilises d3.js and Crossfilter to create interdependent interactive histograms.
JavaScript
60
star
55

babel-plugin-transform-function-composition

Syntactic sugar 🍧🍨🍦 for easy to read function composition. 🦄
JavaScript
58
star
56

preoom

Retrieves & observes Kubernetes Pod resource (CPU, memory) utilisation.
JavaScript
55
star
57

fuss

The Facebook SDK for PHP provides an interface to the Graph API.
PHP
53
star
58

postloader

A scaffolding tool for projects using DataLoader, Flow and PostgreSQL.
JavaScript
51
star
59

moa

MOA implements dynamically generated Active Record database abstraction.
PHP
50
star
60

extract-date

Extracts date from an arbitrary text input.
JavaScript
49
star
61

gitinfo

Gets information about a Git repository.
JavaScript
47
star
62

sister

Foundation for your emitter implementation. 202 reasons to not write your own implementation of event emitter.
JavaScript
45
star
63

react-outside-event

A higher order React component that attaches an event listener for events that occur outside of the component element.
JavaScript
44
star
64

babel-plugin-annotate-console-log

Annotates console.log call expression with information about the invocation context.
JavaScript
42
star
65

react-youtube-player

React component that encapsulates YouTube IFrame Player API and exposes player controls using the component properties.
JavaScript
40
star
66

bundle-dependencies

Generates bundledDependencies package.json value using values of the dependencies property. Updates package.json definition using the generated bundledDependencies value.
JavaScript
39
star
67

facebook-friend-rank

PHP class that can calculate who are the best user's friends. Data accuracy depends on the user activity and granted permissions.
PHP
39
star
68

waitehr

Waits for HTTP response and retries request until the expected response is received.
TypeScript
37
star
69

doll

Extended PDO with inline type hinting, deferred connection support, logging and benchmarking.
PHP
36
star
70

pie-chart

This is a helper function that utilises d3.js to create pie charts.
JavaScript
36
star
71

sguid

Signed Globally Unique Identifier (SGUID) generator.
JavaScript
34
star
72

slonik-utilities

Utilities for manipulating data in PostgreSQL database using Slonik.
TypeScript
32
star
73

prepack-loader

A webpack loader for prepack.
JavaScript
31
star
74

seeql

Real-time SQL profiler.
JavaScript
30
star
75

react-strict-prop-types

A higher order component that raises an error if component is used with an unknown property.
JavaScript
29
star
76

postgres-bridge

postgres/pg compatibility layer
TypeScript
29
star
77

crack-json

Extracts all JSON objects from an arbitrary text document.
JavaScript
29
star
78

roarr-cli

A CLI program for processing Roarr logs.
TypeScript
28
star
79

paggern

Pattern interpreter for generating random strings.
PHP
28
star
80

roarr-browser-log-writer

Roarr log writer for use in a web browser.
TypeScript
27
star
81

cluster-map

Abstracts execution of tasks in parallel using Node.js cluster.
JavaScript
27
star
82

database-types

A generic type generator for various databases.
JavaScript
26
star
83

iapetus

Prometheus metrics server.
TypeScript
25
star
84

require-new

Requires a new module object.
JavaScript
23
star
85

tmdb

The Movie Database (TMDb) SDK.
JavaScript
23
star
86

pan

Touch enabled implementation of WHATWG drag and drop mechanism.
JavaScript
23
star
87

eslint-plugin-zod

Zod linting rules for ESLint.
TypeScript
21
star
88

pragmatist

A collection of tasks to standardize builds.
JavaScript
21
star
89

pianola

A declarative function composition and evaluation engine.
JavaScript
20
star
90

approximate-now

Approximate (fast) current UNIX time.
TypeScript
20
star
91

babel-plugin-transform-export-default-name

Babel plugin that transforms default exports to named exports.
JavaScript
20
star
92

xfetch

A light-weight HTTP client for Node.js.
JavaScript
19
star
93

extract-time

Extracts time from an arbitrary text input.
JavaScript
19
star
94

override-require

Overrides Node.js module resolution logic.
JavaScript
18
star
95

fastify-webpack-hot

A Fastify plugin for serving files emitted by Webpack with Hot Module Replacement (HMR).
TypeScript
18
star
96

canonical

Canonical code style linter and formatter for JavaScript, SCSS, CSS and JSON.
JavaScript
18
star
97

babel-plugin-lodash-modularize

Babel plugin that replaces lodash library import statement to individual module imports.
JavaScript
18
star
98

semantic-url-parser

Extracts content information from known URL patterns.
TypeScript
17
star
99

extract-price

Extracts prices from an arbitrary text input.
JavaScript
17
star
100

express-tus

Express middleware for tus protocol.
JavaScript
16
star