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
| Condition | What to Show | 
|---|---|
| User is logged in | Show profile | 
| User is not logged in | Show login button | 
| API is loading | Show loading spinner | 
| Data is available | Show 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
| Technique | Use Case | Code Example | 
|---|---|---|
| if/else | Complex logic outside JSX | if () { return A } else { return B } | 
| Ternary Operator | Inline short if/else | {condition ? A : B} | 
| && Operator | Only render if condition true | {isLoggedIn && <LogoutButton />} | 
| Early Return | Exit early, skip render | if (!isAdmin) return null; | 
Advertisement Slot 1
Advertisement Slot 2