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

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 set 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