How to conditionally apply class attributes in ReactJS?

When we are writing JSX code often time we need to put class attribute based on some condition. Inside JSX we are not allowed to use if, for or any other statements. On the other hand we are allowed to use expression inside JSX.

As we are allowed to use expression, we can use ternary to apply conditional class inside JSX. Follow are multiple ways of applying class attributes inside JSX in ReactJS.

Approach #1

By using ternary inside class attribute like below we can easily add conditional class. See the code segment below:

<i className={"fas " + (context.state.theme == 'light' ? "fa-moon" : "fa-sun")}></i>

Approach #2

If we have a transpiler (such as Babel or Traceur) available we can use the new ES6 template strings.

<i className={`fas ${context.state.theme == 'light' ? 'fa-sun' : 'fa-moon'}`}></i>
Share