React / React Conditionals / The Ternary Operator
Home /React /React Conditionals /The Ternary Operator

The Ternary Operator

The Ternary Operator condition ? A : B

The ternary operator (condition ? expressionIfTrue : expressionIfFalse) is a compact, inline way to choose between two values or JSX elements. Unlike if/else, it is an expression it produces a value, so it works directly inside JSX curly braces.

The ternary operator is the most commonly used conditional rendering pattern in React. It is ideal when you need to choose between exactly two outcomes. For more than two outcomes, use if/else or switch for readability.

Basic Ternary :Show or Hide

function AuthButton({ isLoggedIn }) {
  return (
    <div>
      {/* Ternary inside JSX — expression on both sides */}
      {isLoggedIn ? (
        <button>Log Out</button>
      ) : (
        <button>Log In</button>
      )}

      {/* Ternary for text content */}
      <p>
        Status: {isLoggedIn ? 'Online 🟢' : 'Offline 🔴'}
      </p>

      {/* Ternary for class names */}
      <div className={isLoggedIn ? 'card active' : 'card inactive'}>
        Dashboard
      </div>
    </div>
  );
}

Ternary with JSX Blocks

function EnrollmentCard({ enrolled, course }) {
  return (
    <div className="card">
      <h3>{course.title}</h3>

      {enrolled ? (
        <div>
          <p>Progress: {course.progress}%</p>
          <button>Continue Learning</button>
        </div>
      ) : (
        <div>
          <p>Not enrolled yet</p>
          <button>Enroll Now</button>
        </div>
      )}
    </div>
  );
}
Avoid Nesting Ternaries: Nested ternaries (a ? b : c ? d : e) become unreadable quickly. If you have more than two outcomes, switch to if/else or a switch statement before the return.

Ternary for Style & Attributes

function StatusBadge({ status }) {
  return (
    <span
      style={{
        background: status === 'published' ? '#D1FAE5' : '#FEF3C7',
        color:      status === 'published' ? '#065F46' : '#92400E',
        padding:    '4px 12px',
        borderRadius: '20px',
        fontSize:   '0.8rem',
      }}
    >
      {status === 'published' ? '✓ Published' : '✎ Draft'}
    </span>
  );
}