[React] Styling

Dynamically Assign Styles

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
render() {
let output = null;

let buttonStyles = {
color: 'white',
backgroundColor: 'green',
font: 'inherit',
border: '1px solid blue',
padding: '8px',
cursor: 'pointer'
}
...

if (this.state.show) {
buttonStyles.backgroundColor = 'red';

...
}

Dynamically Change Classes

1
2
3
4
5
6
7
8
9
// App.css

.red {
color: red;
}

.bold {
font-weight: bold;
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
let classes  = [];

if (this.state.persons.length <= 2) {
classes.push('red');
}

if (this.state.persons.length <= 1) {
classes.push('bold');
}

return (
<div className="App">
<button
onClick={this.toggleHandler}
style={buttonStyles}>Toggle</button>
<p className={classes.join(' ')}>Test</p>
{output}
</div>
);

Use Radium to render qsuedo class

Install Radium npm install --save radium

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
// Component.js

const style = {
margin: '0 auto',
'@media (minWidth: 500px)' : {
width: '450px'
}
}

// In App.js
import Radium, { StyleRoot } from 'radium';
// To use media queries @media...

render() {
let output = null;

let buttonStyles = {
color: 'white',
backgroundColor: 'green',
font: 'inherit',
border: '1px solid blue',
padding: '8px',
cursor: 'pointer',

':hover': {
backgroundColor: 'lightgreen',
color: 'black'
}
}

if (this.state.show) {
buttonStyles.backgroundColor = 'red';
buttonStyles[':hover'] = {
backgroundColor: 'lightred',
color: 'black'
};
}
...

return (
<StyleRoot> // Wrap in <StylsRoot>
<div className="App">
<button
onClick={this.toggleHandler}
style={buttonStyles}>Toggle</button>
<p className={classes.join(' ')}>Test</p>
{output}
</div>
</StyleRoot>
);
export default Radium(App);

Use CSS module

  • With CSS modules, you can write normal CSS code and make sure, that it only applies to a given component.
  • Read more here
  • npm run eject
  • In the config/webpack.config.js find test: cssRegex
  • Replace that section with

    1
    2
    3
    4
    5
    6
    7
    test: cssRegex,
    exclude: cssModuleRegex,
    use: getStyleLoaders({
    importLoaders: 1,
    modules: true,
    localIdentName: '[name]__[local]__[hash:base64:5]'
    }),
  • Restart server

In the App.js

1
2
3
4
5
6
7
8
9
10
11
import classes from './App.css';

return (
<div className={classes.App}>
<button
onClick={this.toggleHandler}
style={buttonStyles}>Toggle</button>
<p className={assigned.join(' ')}>Test</p>
{output}
</div>
);
  • To use Classes globally: :global .Post { ... }