Conditional Rendering

Subject: React

โ“ What is Conditional Rendering?

In React, conditional rendering means displaying different content or components based on a condition โ€” just like if/else works in JavaScript.

โœ… React allows you to render:

  • Entire components
  • Specific JSX elements
  • Fragments of a page

...based on current state, props, or logic.


๐Ÿง  Why Use It?

  • Show different UIs for different states (loading, error, success)
  • Protect routes/pages if user is not logged in
  • Hide or show parts of the UI based on logic

๐Ÿงช Common Real-Life Examples

ConditionWhat to Show
User is logged inShow profile
User is not logged inShow login button
API is loadingShow loading spinner
Data is availableShow content

โœ… 1. Using if/else Logic Outside JSX

๐Ÿงพ Output:


โœ… 2. Using Ternary Operator

๐Ÿ’ก Best for short, inline conditions.


โœ… 3. Using && Operator

๐Ÿ” Renders only if condition is true.


โœ… 4. Early Return in Component

โœ… Clearer than nesting conditions.


โœ… 5. Conditional Component Switching

๐Ÿง  Good for switching large UI blocks.


๐Ÿง  How React Handles It Internally

Means:

Means:


โœ… Real Example: Data + Loading State


๐Ÿ“Œ Summary Table

TechniqueUse CaseCode Example
if/elseComplex logic outside JSXif () { return A } else { return B }
Ternary OperatorInline short if/else{condition ? A : B}
&& OperatorOnly render if condition true{isLoggedIn && <LogoutButton />}
Early ReturnExit early, skip renderif (!isAdmin) return null;

๐Ÿ‘‰ Check the Conditional Rendering Cheat Sheet