Originally published on SimpleFrontEnd.
React library is named after its reactive features. Changes to component’s internal state are almost immediately reflected on the screen.
Data stored in the state object can influence many aspects of your web application, including its appearance.
React allows you to set className values based on conditions, which look at state values. For example, if error state variable is true, then apply ‘error-text’ className. If it is false, apply ‘normal-text’ className value.
In this article, we will show how to conditionally add
className value to an element in React. There may be multiple
className values and multiple conditions as well.
Three different ways to apply a conditional className in React
The focus of this article will be to explain all three approaches to conditionally apply classes in React.
- classnames – An essential utility for anyone who wants to dynamically add className values to React elements. Intuitive syntax can handle even more advanced use cases, like multiple className values and even multiple conditions.
- Ternary operator – Most commonly used approach for setting a conditional className in React. Perfectly fine for basic purposes. May be unreadable if the condition is too complex, or if there are too many conditions. For example, it’s difficult to define a combination of multiple static and conditional className values.
- Template literals – A cleaner, more readable way to apply conditional classes in React without installing external packages. Click here to learn more about using template literals to conditionally customize the appearance of React elements.
Choosing the best approach will depend on how frequently you want to use this feature, complexity of the condition, number of values and so on.
For example, we might want to add className value only if it satisfies two or even three conditions. Or add multiple className values to React elements – some dynamically applied, and others that should always be there. Let’s start with basics and show a simple example of adding a conditional class in JSX.
Full article on SimpleFrontEnd.