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?
<div
className={`
constant1
constant2
${isActive ? "active" : ""}
${isReady ? "ready" : ""}
`}
></div>
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.
<div
className={
classNames({
constant1: true,
constant2: true,
active: isActive,
ready: isReady,
})
}
></div>
We can also pass the constant classes as parameters to this function.
<div
className={
classNames(
"constant1",
"constant2",
{
active: isActive,
ready: isReady
}
)
}
></div>