Start your developer blog today!
Email me

How to Add Classes Dynamically Based on State or Props in React

Jul 28, 2020 2 min read

Adding classes based on some condition is a problem I face quite often in React.

Suppose we wanted to add an active or ready class to a <div> depending on the isActive and isReady states below, respectively.

const [isActive, setIsActive] = useState(false);
const [isReady, setIsReady] = useState(false);

Using Ternary Operator

We can add the class using a simple ternary operator. If isActive is true, then we’ll see className to active, otherwise, there will be no class.

<div className={isActive ? "active" : ""}></div>

What if we want a class to remain constant and another to be dynamic?

<div className={`constant1 ${isActive ? "active" : ""}`}></div>

What if we want multiple constant classes or multiple dynamic ones?

     ${isActive ? "active" : ""} 
     ${isReady ? "ready" : ""}

active will depend on isActive while ready depends solely on isReady.

Using classnames

classnames is a lightweight, JavaScript library for just this purpose.

After installing classnames, we can use the classNames() function.

We can input an object structure, setting constant class names to true and dynamic ones to their respective variables.

      constant1: true,
      constant2: true,
      active: isActive,
      ready: isReady,

We can also pass the constant classes as parameters to this function.

        active: isActive,
        ready: isReady

More JavaScript Articles