I am trying to create a button ponent with styled-system and styled-ponents.
The variants of styled-system works great, but I am wondering how to add conditional css. For example, I am trying to render primary block button.
const StyledButton = styled(Button)`
${props => props.block && css`width: 100%;`
`;
// primary
<StyledButton block variant="primary" />
This works as expected, but I would like to know if there is any better way to apply block
in beautiful way with pure javascript.
I am trying to create a button ponent with styled-system and styled-ponents.
The variants of styled-system works great, but I am wondering how to add conditional css. For example, I am trying to render primary block button.
const StyledButton = styled(Button)`
${props => props.block && css`width: 100%;`
`;
// primary
<StyledButton block variant="primary" />
This works as expected, but I would like to know if there is any better way to apply block
in beautiful way with pure javascript.
3 Answers
Reset to default 3I think you can shorten your specific example as follows (you don't need to use css
method there):
const StyledButton = styled(Button)`
${({block}) => block && 'width: 100%;'}
`;
But generally, I believe this is the only way of doing it. Doesn't really look ugly to me, but if you have some plex conditions you can probably move some code into separate variables or functions with descriptive names.
You can create a mixin and add it conditionally. You just need to import css from Styled-ponents. For example:
const buttonWidthMixin = css`
width: 100%
`
Then you can add it to the button like so:
const StyledButton = styled(Button)`
${props => props.block && buttonWidthMixin};
`
Now if you add block prop to the button it will add our new mixin to css.
It is possible to return styles as json object this way:
const StyledButton = styled(Button)`
${({block}) => block && {width: '100%'}}
`;