Styled-components 3 ways

Style Objects

1const Button = styled.button((props) => ({
2  color: props.color,
3  border: `2px solid ${props.border}`,
4  background: props.background,

styled-components optionally supports writing CSS as JavaScript objects instead of strings. This is particularly useful when you have existing style objects and want to gradually move to styled-components.

Tagged Template Literals

1const Button = styled.button`
2  color: ${(props) => props.color};
3  border: 2px solid ${(props) => props.border};
4  background: ${(props) => props.background};

Tagged Template Literals are a new feature in ES6. They let you define custom string interpolation rules, which is how we’re able to create styled components.

If you want to learn more about tagged template literals, check out Max Stoiber’s article: The magic behind 馃拝馃従 styled-components

And the third one…

But apparently, there is a third way which is not documented:

1const Button = styled.button((props) => `
2  color: ${props.color};
3  border: 2px solid ${props.border};
4  background: ${props.background};

When I saw it the first time, I thought this was an error and it would not work. Actually, it does. From my POV it’s more readable than “Tagged Template Literals”.

I wonder why it’s not listed in the official documentation.

Except where otherwise noted, content on this site is licensed under Creative Commons Attribution-NonCommercial-ShareAlike 4.0