0
0
ReactHow-ToBeginner · 3 min read

How to Conditionally Apply Class in React: Simple Guide

In React, you can conditionally apply a class by using JavaScript expressions inside the className attribute. Use a ternary operator or logical AND to add a class only when a condition is true, like className={isActive ? 'active' : ''}.
📐

Syntax

Use the className attribute in JSX to assign CSS classes. Inside it, use JavaScript expressions with ternary operators or logical operators to decide which class to apply.

  • condition ? 'class-if-true' : 'class-if-false' applies one class or another based on the condition.
  • condition && 'class-if-true' applies the class only if the condition is true.
jsx
const isActive = true;

return <div className={isActive ? 'active' : 'inactive'}>Hello</div>;
Output
<div class="active">Hello</div>
💻

Example

This example shows a button that toggles its active state. The button's class changes based on whether it is active or not, demonstrating conditional class application.

jsx
import React, { useState } from 'react';

export default function ToggleButton() {
  const [isActive, setIsActive] = useState(false);

  return (
    <button
      className={isActive ? 'btn active' : 'btn'}
      onClick={() => setIsActive(!isActive)}
      aria-pressed={isActive}
    >
      {isActive ? 'Active' : 'Inactive'}
    </button>
  );
}
Output
<button class="btn">Inactive</button> (click toggles to <button class="btn active">Active</button>)
⚠️

Common Pitfalls

Common mistakes include:

  • Using class instead of className in JSX, which won't work.
  • Not returning a string from the conditional expression, causing invalid class names.
  • Forgetting to handle the false case in ternary operators, leading to unwanted classes.

Always ensure the expression inside className results in a valid string or empty string.

jsx
/* Wrong way: */
return <div className={isActive ? 'active' : ''}>Hello</div>;

/* Right way: */
return <div className={isActive ? 'active' : ''}>Hello</div>;
📊

Quick Reference

Tips for conditional classes in React:

  • Use className attribute, never class.
  • Use ternary condition ? 'class1' : 'class2' for two options.
  • Use logical AND condition && 'class' to add a class only if true.
  • Combine multiple classes with template literals: `base ${condition ? 'extra' : ''}`.
  • Consider libraries like clsx or classnames for complex cases.

Key Takeaways

Use the className attribute with JavaScript expressions to apply classes conditionally in React.
Ternary operators and logical AND are simple ways to toggle classes based on state or props.
Always return valid strings for class names to avoid rendering issues.
Never use the HTML attribute class; always use className in JSX.
For complex class logic, consider helper libraries like clsx or classnames.