The Modern Way to Style with Styled Components

An in-depth look at the power of Styled Components

By Michael Chang

September 15th, 2020

image

My Journey

Like many, I first started styling React with inline CSS. It was an adjustment coming from stylesheets but I really liked the ability to define localized styles and leverage the power of Javascript. Of course, there were issues such as performance and lack of pseudo-selector support, but overall I was happy with it and there was no compelling reason or deficiency to search for another way to style my components.

When I was first introduced to Styled Components, I was a bit apprehensive of the benefits, having gotten used to inline CSS for so long. After all, React documentation (at the time), still used inline CSS for all their examples. As I prototyped the framework, I discovered a best of both worlds between inline CSS and traditional stylesheets.

Styled Components

While defined very differently, Styled Components act fundamentally like React components. They both take props as input and output HTML.

Let’s take this sample button component styled similarly to Bootstrap’s buttons with Styled Components.

import styled from 'styled-components';

const Button = styled.button`
  display: inline-block;
  padding: 6px 12px;
  font-size: 16px;
  font-family: Arial, sans-serif;
  line-height: 1.5;
  color: white;
  background-color: #6c757d;
  border: none;
  border-radius: 4px;

  :not(:disabled) {
    cursor: pointer;
  }

  :hover {
    background-color: #5a6268;
  }
`;

The styled component factory is imported and used to generate a button with styles using a template literal (...). This factory supports all valid HTML elements whether that be div, h1, p, etc. Similarly, the styles in the template literal accepts all valid CSS so you can go crazy with complex CSS selectors.

Usage

Once defined, they act exactly like React components and are used in the exact same way — JSX. After all, Styled Components are simply React components with some styling.

const App = () => {
  return (
    <Button onClick={() => alert('clicked!')} type="button">
      Button
    </Button>
  );
};

Styled Component ButtonStyled Component Button

Just like React components, Styled Components also accepts props and are defined in the same exact way. Styled Components will pass all (valid) DOM properties to the DOM.

Internals

Okay, so how does this work? What wizardly process is happening internally?

  1. At render, Styled Components will generate a unique classname based on the defined styles.

  2. Styled Components will inject a style tag (