Another Styled Component Pattern
May 19, 2020
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:
I've found you can further simplify this! This is how I write my styled-components now: pic.twitter.com/LTQJfG96o1
— Drake @ PDX (@Saeris) May 18, 2020