Style Objects
const Button = styled.button((props) => ({
color: props.color,
border: `2px solid ${props.border}`,
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
const Button = styled.button`
color: ${(props) => props.color};
border: 2px solid ${(props) => props.border};
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:
const Button = styled.button((props) => `
color: ${props.color};
border: 2px solid ${props.border};
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".
Top comments (5)
Unfortunately no clean way to get syntax highlighting for the third option - at least in VSCode.
Other than that though, yeah, this is a very common way to access props and it's a very well hidden trick indeed.
It works in TypeScript though:
Ran into quite a few issues and limitations sadly.
The
css
interpolation function is still required if you want to execute logic statements or curried functions. Slightly more info in the official docs: styled-components.com/docs/api#cssAlso the syntax highlighting breaks if you place the opening backtick that comes after
(props) =>
on a new line. UnfortunatelyPrettier
automatically places the entire inner interpolation function on its own line grrr 😝simple template literal (without
css
):Sadly, but yes highlighting is broken in many cases
Huh, neat, thanks for sharing! Looks like syntax highlighting does indeed play nice when you add any sort of typings.
Guess what I'll be working on this Monday morning :)