Reputation: 319
Just for curiosity, I am using styled-components in my React application and in there I use the suggested theme to have all colors and sizes everywhere available.
Currently I am doing it like this:
export const TestComponent = styled.div`
color: ${({ theme }) => theme.white};
background-color: ${({ theme }) => theme.white};
border: 1px solid ${({ theme }) => theme.white};
display: ${({ check }) => check ? 'block' : 'none'};
`;
So I am using the theme from the ThemeProvider
and also an additional check of the outside component.
My question is now, why can I not use it like this:
export const TestComponent = styled.div`${({ theme, check }) => (css`
color: ${theme.white};
background-color: ${theme.white};
border: 1px solid ${theme.white};
display: ${check ? 'block' : 'none'};
`)`;
Wouldn't it be more convenient and easier to use ? And if so, why aren't they not suggesting it like this? I am just afraid that it hast some huge disadvantage, which I cannot see right now.
Upvotes: 0
Views: 681
Reputation: 1339
I don't believe there's anything wrong with either approach. I've used what you're doing in your first example a lot in a large React app, and had no issue (yet).
That being said, your second example is perfectly valid. You don't even need the css
helper:
const Test = styled.div`
${({ theme }) => `color: ${theme.white};`}
`;
In general, I use the css
helper to create abstracted/sharable css chunks:
const fontSize = css`
font-size: ${({ small, large, theme }) => {
if (small) return `${theme.small}rem`;
if (large) return `${theme.large}rem`;
return `${theme.normal}rem`;
}};
`;
const Test = styled.div`
${({ theme }) => `color: ${theme.white};`}
${fontSize}
`;
And then:
<Test small>Hello World</Test>
Upvotes: 1