OnlineCBT Logo OnlineCBT
React Tutorial
REACT · LESSON 6

Conditional Rendering

By Ratan Updated: 16 Oct 2026

Render different UI elements dynamically using ternary operators, && short-circuiting, and switch blocks.

Level: Beginner to Advanced
Duration: ~60 Mins Deep-Dive

1. Why Conditional Rendering?

In web applications, the UI must adapt to different states: showing a loading spinner while fetching questions, displaying an error banner when network fails, or toggling between "Login" and "Logout" buttons.

2. Pattern 1: if...else Statements

Best for early returns when entire component views differ:

function ExamResult({ score, passingScore = 50 }) {
  if (score === null) {
    return 

Evaluation pending...

; } if (score >= passingScore) { return
Congratulations! You Passed.
; } else { return
Needs Improvement. Try Again.
; } }

3. Pattern 2: Ternary Operator (condition ? trueJSX : falseJSX)

Ideal for concise inline branching inside JSX:

function TestHeader({ isTimeWarning, remainingSeconds }) {
  return (
    
      

Final Assessment

{remainingSeconds < 60 ? "Less than 1 min left!" : `Time: ${Math.floor(remainingSeconds / 60)} mins`}
); }

4. Pattern 3: Logical AND (&&) Operator

Use when you want to render an element only when a condition is true, and render nothing otherwise:

function NotificationBell({ unreadNotifications }) {
  return (
    
🔔 {/* Renders badge only if unread notifications exist */} {unreadNotifications > 0 && ( {unreadNotifications} )}
); }
Gotcha Notice: Avoid writing {messages.length && } if length is 0, because JavaScript evaluates 0 && ... to 0, printing a literal "0" onto the screen. Always use boolean coercion: {messages.length > 0 && }.

5. Preventing Rendering by Returning null

If a component should render nothing at all under certain conditions, return null:

function WarningModal({ isOpen, message }) {
  if (!isOpen) return null; // Component does not render
  return 
{message}
; }

📝 Live Lesson Practice

HTML/CSS JavaScript Python C++ C PHP
⌨️ Practice Inputs (लाइव इनपुट भरें) (खाली होने पर RED, भरने पर GREEN underline)
💻 Code Editor (Monaco VS Code Engine)
👀 Live Preview
पता संपर्क करें

+91 7877547686

ई-मेल

onlinecbtportal@gmail.com

हेल्पलाइन नंबर

+91 7877547686


डाउनलोड करने के लिए क्लिक करें
Get it on Google Play

ऐप डाउनलोड करने
के लिए Google Play पर
उपलब्ध है

WhatsApp Chat