Hackforge Academy

Category: react

conditional class in react

Published on 22 Apr 2026

Explanation

Use a ternary operator to apply a class based on a condition. This is the most common method in React.

Code:

const isActive = true;

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

Explanation

Use logical AND (&&) when adding a class only if a condition is true.

Code:

const isError = true;

<div className={isError && "error"}>
Message</div>

Explanation

Combine multiple classes conditionally using template literals for dynamic styling.

Code:

const isActive = true;

<div className={`btn ${isActive ?
 "btn-primary" : "btn-secondary"}`}>
  Click Me
</div>

Explanation

Apply multiple conditions using template literals for flexible UI styling.

Code:

const isActive = true;
const isDisabled = false;

<div className={`btn ${isActive ? 
"active" : ""} ${isDisabled ? 
"disabled" : ""}`}>
  Button
</div>

Explanation

Use the classnames library to manage complex conditional classes in large applications.

Code:

import classNames from "classnames";

const isActive = true;

<div className={classNames("btn",
 { active: isActive })}>
  Button
</div>

Explanation

Conditional classes are commonly used for toggling dark mode, validation states, active menu items, and button states in React apps.

Code:

// Example use cases:
// Active navbar link
// Form validation error highlight
// Dark mode toggle

πŸš€ Learn Spring Boot with real-world projects

πŸ’‘ Build REST APIs step by step

🧠 Improve backend development skills

🎯 Get career-ready practical training

Join Our Free WhatsApp Community

Direct access to niche-specific mentors and peers on WhatsApp.

🐍

Python Community

Discuss Django, FastAPI, AI integration, and automation scripts with 15k+ developers.

Join Python Community
βš›οΈ

React Community

Master Next.js, Framer Motion, and State Management. Share your latest UI components.

Join React Community
β˜•

Java Community

Deep dives into Spring Boot, Microservices architecture, and high-performance backend ops.

Join Java Community