What’s the deal with CSS and CSS‑in‑JS?
They can do a lot of the same things, but in different ways.
Many people like CSS‑in‑JS because it lets them manage code at the component level and have a productive workflow.
There are lots of CSS‑in‑JS libraries out there. I like Styled System because it makes it easy for me to use a responsive design system.
Build components with style props applied to the components themselves.
<Header textAlign="center" py={4}>
<H1 fontSize={[3,5]}>Hello there. I’m built with CSS in JS.</H1>
</Header>
You can use fancy new CSS features with CSS‑in‑JS. The idea that you don’t need to know CSS to do CSS‑in‑JS is not true. CSS‑in‑JS is still CSS!
const Wrapper = styled.div`
color: #fff;
padding: 1vw;
display: grid;
grid-gap: 1vw;
grid-template-columns: 32vw 32vw 32vw;
grid-template-areas:
"header header header"
"sidebar main main"
"footer footer footer";
@media screen and (max-width: 60em) {
grid-template-areas:
"header header header"
"main main main"
"sidebar sidebar sidebar"
"footer footer footer";
}`
With CSS-in-JS your styling can change based on state or props passed to your components.
<Button onClick={this.props.changeColor} color={this.props.color}>change color</Button>
export default class extends React.Component {
constructor() {
super()
this.colors = ['#00ADEF','#22AD00','#FF8C00','#ee5555','#484fd1']
this.state = { colorIndex: 0 }
this.changeColor = this.changeColor.bind(this)
}
changeColor(e) {
this.setState({ colorIndex: (this.state.colorIndex+1) % this.colors.length })
}
...
This is all very new and it can be a challenge to keep up. If you like trying new things and want to build websites this way, there’s nothing wrong with that and don’t let anyone stop you!