conditional classNames in React
In this article, I want to talk about conditional styling in React. Specifically, about setting multiple className values conditionally. A lot of beginner React developers get confused about conditional classnames, especially if there are multiple values involved.
Setting className in JSX
Otherwise, the syntax of setting className to a React element looks pretty similar to HTML. Value looks like a string. To set multiple values, you simply separate them by a space.
Conditional className in JSX
Now, let’s talk about state. Most of the time, we implement conditional classes to respond to changes in the state. For example, user toggles the ‘Dark Mode’ switch. If you know controlled components, you should know that typically input elements are tied to state values in React. So changes in input triggers changes in the state.
So when you define multiple conditional className values, you need to look at state value. Depending on the current value of the state variable, you should determine the class. You can do that in multiple ways. The easiest is to use a ternary operator, which works like this: first, we write a condition, followed by a question mark. Then we the value to be returned if the condition is true. Then follow it up by a semicolon and write an alternative value, if the condition is false. Once you get used to it, ternary operators are really easy to write.
You can also write a function that takes a state variable as an argument and returns a certain combination of className values. Then set className attribute to the result of that function.
classnames() function for handling multiple conditional className values
Finally, there are also various external utilities and libraries for setting conditional className values in React. The classnames utility is the best one I know. You can use it for advanced use cases. For example, when you want two values to be always applied, and three conditional values. You can do that with the classnames() function.
SimpleFrontEnd has excellent guide on setting multiple className values conditionally in React.
General classes or specific classes?
Experienced developers define many classes, and apply combinations of these classes to great effect. This gives us more flexibility to style elements without writing too much and complicated classes. Similarly, you should aim to define as few classes as possible, and reuse them to achieve the desired goal.