Skip to content

Instantly share code, notes, and snippets.

@AgtLucas
Forked from istarkov/00 README.md
Created November 24, 2015 00:46
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save AgtLucas/d859ea7d50c6da77aa47 to your computer and use it in GitHub Desktop.
Save AgtLucas/d859ea7d50c6da77aa47 to your computer and use it in GitHub Desktop.
How to style React components

How to style React components

If you use sass and css-modules and want to restyle some base component without changing its code. (base component already use css-modules and exposes styles property)

I know two way how to do it.

  1. Using composes css-modules operator just extend classes you need, then in javascript code combine both styles as {...baseStyle, ...myStyleSimple}

example: myStyleSimple.sass, howToUseWithDifferentStyles.jsx

  1. Using @import sass directive just copy base style and use it as usual.

example: myStyle.sass, howToUseWithDifferentStyles.jsx

  • Pros: No need to do any operations in js
  • Cons: Full style copy, no code reuse

PS: webpack loader config part

import React from 'react';
import baseStyles from './base.sass';
export default ({styles=baseStyles}) => (
<div className={styles.main}>
<div className={styles.someOtherStyle}>
HELLO WORLD
</div>
</div>
);
import React from 'react';
import BaseComponent from './BaseComponent.jsx';
import baseStyles from './base.sass';
import myStyleSimple from './myStyleSimple.sass';
import myStyles from './myStyle.sass';
export default () => (
// using base classes
<BaseComponent styles={baseStyles} />
// using css-modules composition
<BaseComponent styles={{...myStyleSimple, ...baseStyles}} />
// using copied and extended style
<BaseComponent styles={myStyles} />
);
.main
width: 100%
height: 100%
background-color: blue
.someOtherStyle
...
...
.main
composes: main from "./base.sass";
background-color: red
// create a copy of base.sass
@import './base.sass'
// With css-modules this will not change
// styles of controls which uses base.sass
.main
background-color: red
// webpack loader example
module: {
loaders: [
{
test: /\.sass$/,
loader:
'style-loader!' +
'css-loader?modules&importLoaders=2&localIdentName=[name]__[local]--[hash:base64:3]!' +
'postcss-loader!' +
'sass-loader?precision=10&indentedSyntax=sass'
},
...
]
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment