styled-components - The best CSS-in-JS library for React

Styled-components is an open-source JavaScript library for styling React and React Native components by allowing you to write actual CSS in your JavaScript code. It relies on ECMAScript tagged template literals under the hood.

This technique will seem counter-intuitive at first, since the whole point of using CSS instead of directly styling HTML elements is to decouple styles and markup by introducing this intermediary class layer. But that decoupling causes many problems for CSS at scale.

If you’re already convinced by the benefits of component-based frontend architecture and CSS-in-JS styling technique then styled-component is the perfect choice with easy setup, server-side rendering, theming, great documentation and tooling.

Let’s say you want to create a simple <Button /> component that has a normal version and a primary version for the important buttons. Here is the example code in React:

// MyComponent.js
import React from 'react'
import styled from 'styled-components'

const Button = styled.button`
  background: transparent;
  border-radius: 3px;
  border: 2px solid red;
  color: red;
  margin: 0.5em 1em;
  padding: 0.25em 1em;

  ${(props) =>
    props.primary &&
    css`
      background: red;
      color: white;
    `}
`

const Container = styled.div`
  text-align: center;
`

const MyComponent = () => (
  <Container>
    <Button>Normal Button</Button>
    <Button primary>Primary Button</Button>
  </Container>
)

export default MyComponent