How to conditionally apply class names in React
In this tutorial, we are going to learn about how to apply class names to the element based on the particular condition in React.
Using the ternary operator
We can add or remove class names conditionally by using the JavaScript ternary operator.
Here is an example:
import React, { useState } from "react";
import "./styles.css";
export default function App() {
const [isActive,setActive] = useState(true);
return (
<div className={isActive?"green-box":"red-box"}> <h1>Hello React</h1>
<button onClick={()=>setActive(!isActive)}>Change color</button> </div>
);
}
In the above code, we have added following ternary condition isActive ? "green-box":"red-box"
to div
element.
If isActive
property is true
, we are applying green-box
class to the div element else we are applying red-box
.
In some cases, you already have a one class name to the div
element and you need to apply other class-names conditionally.
We can do it by using a ternary operator inside a template literal.
import React, { useState } from "react";
import "./styles.css";
export default function App() {
const [isActive,setActive] = useState(true);
return (
<div className={`container ${isActive?"green-box":"red-box"}`}> <h1>Hello React</h1>
<button onClick={()=>setActive(!isActive)}>Change color</button>
</div>
);
}
In the above code, there is already a container
class in the div
element and we are applying green-box
or red-box
classes conditionally.
Applying class name only if condition is true
If you want to apply a class name only if the condition is true, you can do it by setting a second expression to null
or undefined
in the ternary operator.
Example:
import React, { useState } from "react";
import "./styles.css";
export default function App() {
const [isActive,setActive] = useState(true);
return (
<div className={isActive? "green-box" : null}> <h1>Hello React</h1>
<button onClick={()=>setActive(!isActive)}>Change color</button>
</div>
);
}
Now, the green-box
class is applied to the div
element only if isActive
property is true else nothing is applied.