Chandler Moisen

TIL: Another Styled Component Pattern

TIL: Another Styled Component Pattern

Today I learned yet another styled-components pattern.

styled-components is an approach to writing CSS within JavaScript. It uses tagged template literals to enable the following:

import styled from 'styled-components'

const Button = styled.button`
  color: #0974EC;

  &:hover {
    color: #EC2509;
  }
`

A great feature of styled-components is that you can wrap your application in a global theme provider and each styled component instance has access to:

import styled from 'styled-components'

const Button = styled.button`
  color: ${({ theme }) => theme.color.blue};

  &:hover {
    color: ${({ theme }) => theme.color.red};
  }
`

While there is a whole debate to be had about the CSS-in-JS approach, I have found working with styled-components to be mostly pleasant save one aspect: having to pollute my components with the interpolated ${({ theme }) => in order to access the global theme. I have found that I am often using this interpolation 5+ times for each styled component I build 😱.

That all changed today: