- Put all CSS classes into an array.
- Use a ternary operator to set an empty string as a class when the condition is
- Join the array using spaces, to convert it into a
Here's how it's done:
A utility function to join classes
There are two ways we can improve on the basic approach:
&&operator to set classes only on truthy values.
- Filter out the falsy values from className array before joining them.
We can write a reusable function we can use to generate the `className` string with the above improvements. Here it is:
: any part from the function parameters.
classNames utility function can be used to apply the classes conditionally in React like so:
Here's how the CSS classes look like in
border: 1px dashed black;
This is what it looks like when we click the button:
Feel free to use the
classNames utility I've shown to help join the classes into the string. Then, to conditionally apply the class, simply use
&& operator after the condition.
Find the full example code in my GitHub repo.
Here's a course on React that will teach you how to build something more than another to-do app (finally, am I right?):