CSS modules
in ReactJS


Webpack

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

import React from 'react';
import styles from './sidebar.scss';
function Sidebar({ user }) {
return <div>
<span className={styles.name}>{user.firstName} {user.lastName}</span>
<img className={styles.avatar} src={user.avatarUrl} />
</div>
}
export default Sidebar;css-loader
.name {
color: green;
}
.avatar {
width: 100px;
height: 100px;
}.1293847102983-name {
color: green;
}
.1234123412341-avatar {
width: 100px;
height: 100px;
}styles.name == '1293847102983-name'
styles.avatar == '1234123412341-avatar'css-loader has few 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.
import React from 'react';
import CssModule from 'react-css-modules';
import styles from './sidebar.scss'
function Sidebar({ user }) {
return <div>
<span styleName='name'>{user.firstName} {user.lastName}</span>
<img styleName='avatar' src={user.avatarUrl} />
</div>
}
export default CssModule(Sidebar, styles);react-css-modules
CSS modules!
${this.styles = require('./index.css'), ""}
<div class="${this.styles.logo}">
Hello world
</div>
(requires "interpolate" flag for html-loader)
/* index.css */
.logo {
color: red;
}<div class="_3gBJbu7o592GGUQ4CjIQTM">
Hello world
</div>._3gBJbu7o592GGUQ4CjIQTM {
color: red;
}Thank you
sheerun@sher.pl
I have jobs for:
- 2 Ruby & Rails seniors (Rome travel!)
- 2 JavaScript developers (React)
European Salary
Copy of CSS modules in ReactJS
By Adam Stankiewicz
Copy of CSS modules in ReactJS
- 1,184