Chapter 7: Conditional Rendering

1. What is Conditional Rendering?

Conditional rendering means showing different JSX based on a condition. In React, you never use if statements directly inside JSX (because JSX is not JavaScript code block). Instead, we use JavaScript expressions that return JSX (or null or nothing).

The 3 most common & clean ways in 2026:

Method Best used when… Example syntax
Ternary operator Show one thing OR another thing {condition ? <ThingA /> : <ThingB />}
&& operator Show something only if condition is true {condition && <Thing />}
If-else outside JSX Complex logic or multiple branches Write if before return

2. Ternary Operator (Most Common & Readable)

Syntax:

tsx

Real example: Login / Logout button

Create src/components/AuthButton.tsx

tsx

3. && Operator (Show ONLY if condition is true)

Syntax:

tsx

Short-circuit evaluation: If condition is false, nothing after && is rendered.

Real example: Loading Spinner + Error Message

tsx

4. If-Else Outside JSX (For Complex Logic)

Sometimes you want to decide what to return before the return statement.

tsx

5. Conditional Rendering of Lists

Very common: show a list only if there are items, otherwise show “empty state”.

tsx

Summary – Chapter 7 Key Takeaways

  • Use ternary? : when you want to choose between two things
  • Use && when you want to show something only if condition is true
  • Put complex logic with if/elsebefore the return statement
  • For lists → check length first → show list or empty state message
  • Return null if you want to show nothing at all
  • All conditions must be JavaScript expressions (no statements like if inside JSX)

Mini Homework Create a ProductCard component that:

  • Takes props: name, price, inStock (boolean)
  • Shows:
    • Green “In Stock” badge if inStock === true
    • Red “Out of Stock” badge if false
    • “Add to Cart” button only if inStock === true
    • Grayed out button + message if out of stock

You may also like...

Leave a Reply

Your email address will not be published. Required fields are marked *