Conditional Styling with Styled Components in React
As I learn more about styled-components, I start using them for more advanced styling and do conditional styling with them in React. The syntax might look a bit scary in the beginning, but once you got the hang of it, it gives you a lot more possibilities to do conditional styling than CSS.
A simple case
Let’s say, we want to conditionally change the color of a div. It will be displayed green, if a task is completed and otherwise red.
We can use props and the ternary operator for the conditional styling in React. Like so ${props => props.completed ? 'green' : 'red'}
So let’s create two StyledDivs with a prop. You can call the prop however you want. Let’s call it “completed”. In the first case, completed is true and and the second case it’s false.
The output will look like this:
Multiple conditions
It’s simple to expand your code and use multiple conditions instead of a simple if/else-condition.
In the following example, Icreated three StyledDivs with the prop “category”. They will be displayed each with a different background-color according to which category they belong to. To achieve this, we only have to add more cases to our ternary operator in line 10–14.
Note that the fourth StyledDiv doesn’t belong to any category. It will get the default background-color “orange” defined in line 14.
This will be the result:
You can do this with any CSS property you want and there are endless possibilities how to use great feature of styled-components.