Managing CSS in React Applications
Styling solution fatigue...
*bit of a misnomer
"Raw/vanilla" CSS is FREE and available everywhere, no buy-in, no strings.
Sass/SCSS is preprocessed CSS with superpowers.
// CSS
nav {
background: red;
}
nav ul {
margin: 0;
padding: 0;
list-style: none;
}
nav li {
display: inline-block;
}
// SCSS
nav {
background: red;
ul {
margin: 0;
padding: 0;
list-style: none;
}
li { display: inline-block; }
}
Common patterns:
Separate styles directory - styles live together, components live elsewhere
Common patterns:
"Sidecar style" - Component is accompanied by Sass file, styles usually scoped to component using a root class name
Runtime variables can be achieved using native Custom CSS Properties
Creates unique class names scoped locally by default, exposes a JS map
Can go hand-in-hand with Sass/Less and custom CSS properties as best-of-both-worlds "CSS-in-JS" option
// Button.module.css
.error {
background-color: red;
}
// another-stylesheet.css
.error {
color: red;
}
// Button.js
import React, { Component } from 'react';
import styles from './Button.module.css'; // Import css modules stylesheet as styles
import './another-stylesheet.css'; // Import regular stylesheet
class Button extends Component {
render() {
// reference as a js object
return (
<button className={styles.error}>
Error Button
</button>
);
}
}
// ...
return (
// ...
<Button
className={
props.active
? styles.active
: styles.default
}
/>
// ...
)
Exposes React component factories using tagged template literal syntax
Styles get dynamically injected into <head>
Wrap React components with `styled` to add styling
const Button = styled.button`
background: transparent;
border-radius: 3px;
border: 2px solid palevioletred;
color: palevioletred;
margin: 0.5em 1em;
padding: 0.25em 1em;
${props => props.primary && css`
background: palevioletred;
color: white;
`}
`;
const Container = styled.div`
text-align: center;
`
render(
<Container>
<Button>Normal Button</Button>
<Button primary>Primary Button</Button>
</Container>
);
Demo time!
$ git clone https://github.com/mvasigh/react-styled-example.git
$ cd react-styled-example
$ npm install
$ npm start