React.js course ยท Lecture 6 of 27

Conditional Rendering

A masterclass tutorial covering if/else statements, Ternary Operators, Logical AND (&&), Logical OR (||), Multiple conditions, Conditional Component Trees, Loading UI Spinners, Empty Data States, Error States, Pitfalls, and Interview Questions.

  • 30 min read
  • Beginner to Intermediate
  • 10 topics
  • 20 Sept 2026
  • Ravindra Nath Jha

What is Conditional Rendering?

In web applications, the user interface is rarely static. Depending on user actions, login permissions, API response statuses, or device states, components must render completely different HTML output.

Conditional Rendering in React means displaying different UI components or markup based on specific conditions or state variables.

Analogy:

Think of conditional rendering like a traffic light. If the signal is green, show the GO signal. If the signal is red, show the STOP signal.

Why Do We Need Conditional Rendering?

Real-world web applications rely on dynamic states:

  • Authentication State: Show <UserDashboard /> if logged in; show <LoginForm /> if logged out.
  • Async API Data Fetching: Show <LoadingSpinner /> while fetching, <ErrorMessage /> on failure, <EmptyState /> if 0 results return, or <DataGrid /> on success.
  • Permission Roles: Show an "Edit / Delete" button for Admin users, but hide it for regular members.

Syntax Option 1 โ€” Standard if / else Statements

You can use standard JavaScript if and else statements *outside* the JSX return statement inside your component function body.

JavaScript
function AuthNotification({ isLoggedIn, username }) {
  if (isLoggedIn) {
    return <div className="welcome-banner">Welcome back, {username}! ๐Ÿ‘‹</div>;
  } else {
    return <div className="login-banner">Please log in to continue. ๐Ÿ”’</div>;
  }
}

Syntax Option 2 โ€” Ternary Operator (condition ? true : false)

The Ternary Operator is the most popular inline conditional rendering pattern in React because it can be embedded directly inside JSX curly braces {}.

Syntax:

{condition ? <TrueComponent /> : <FalseComponent />}

JavaScript
function UserHeader({ user }) {
  return (
    <header className="header">
      <h1>My App</h1>
      {user ? (
        <button onClick={logout}>Log Out ({user.name})</button>
      ) : (
        <button onClick={login}>Log In</button>
      )}
    </header>
  );
}

Syntax Option 3 โ€” Logical AND Operator (&&)

When you want to render a piece of UI only if a condition is true, and render nothing when it is false, use the Logical AND (&&) operator.

How Logical Short-Circuiting Works:

In JavaScript, true && expression evaluates to expression, whereas false && expression evaluates to false (which React ignores and renders nothing).

JavaScript
function Mailbox({ unreadMessages }) {
  return (
    <div className="mailbox">
      <h2>Inbox Overview</h2>
      {unreadMessages.length > 0 && (
        <span className="badge">You have {unreadMessages.length} unread messages! โœ‰๏ธ</span>
      )}
    </div>
  );
}

Syntax Option 4 โ€” Logical OR Operator (||) & Fallbacks

Use the Logical OR (||) operator to provide default fallback text or components when a value is null, undefined, or empty string.

JavaScript
function ProfileName({ displayName }) {
  return (
    <h3>User: {displayName || "Anonymous Developer"}</h3>
  );
}

Handling Multiple Complex Conditions (Switch & Early Returns)

When managing multi-state UI (e.g., loading, error, empty, success), nesting multiple ternary operators leads to unreadable "ternary spaghetti code".

Instead, use Early Returns or a helper switch block before returning JSX:

JavaScript
function UserFeed({ status, data, errorMessage }) {
  // Early Return 1: Loading State
  if (status === 'loading') {
    return <div className="spinner">Loading user data... โณ</div>;
  }

  // Early Return 2: Error State
  if (status === 'error') {
    return <div className="error-alert">Error: {errorMessage} โŒ</div>;
  }

  // Early Return 3: Empty State
  if (status === 'success' && data.length === 0) {
    return <div className="empty-box">No records found. Create your first item! ๐Ÿ“ญ</div>;
  }

  // Main Render: Success Data Grid
  return (
    <ul className="data-grid">
      {data.map(item => <li key={item.id}>{item.title}</li>)}
    </ul>
  );
}

Common Mistakes & Pitfalls in Conditional Rendering

  1. The Falsy Zero Bug (0 && <Component />):

In JavaScript, 0 && <Component /> evaluates to 0. React renders the number 0 onto the browser screen!

  • โŒ Wrong: {items.length && <List />} (renders 0 when length is zero)
  • โœ… Correct: {items.length > 0 && <List />} or {Boolean(items.length) && <List />}
  1. Nested Ternary Spaghetti:

Avoid writing {cond1 ? (cond2 ? <A /> : <B />) : <C />}. Extract conditions into separate sub-components or guard functions.

  1. Causing Side Effects Inside Conditions:

Never trigger state updates (setCount()) or API calls directly inside JSX conditional branches.

Top React Interview Questions on Conditional Rendering

Q1: What does React render when a condition evaluates to null, undefined, or false?

*Answer*: React renders nothing (blank space) without throwing errors.

Q2: Why does 0 && <Child /> display 0 on screen?

*Answer*: In JavaScript, short-circuit evaluation of 0 && expression yields 0. Since 0 is a valid number in React, React displays it on screen. Always use boolean comparisons (length > 0).

Q3: How do you return early from a component based on props?

*Answer*: Perform an if check at the top of the function and return null or a loading fallback component.

Practical Hands-On Exercise โ€” Complete Async Data State Manager

Here is a complete, interactive component managing Loading, Error, Empty, and Success states with custom toggle controls:

JavaScript
// Complete Masterclass Conditional Rendering Showcase (src/App.jsx)
import React, { useState } from 'react';

export default function App() {
  const [viewState, setViewState] = useState('success'); // 'loading' | 'error' | 'empty' | 'success'
  const sampleProducts = [
    { id: 1, name: "React 18 Masterclass Book", price: 999 },
    { id: 2, name: "Next.js Fullstack Guide", price: 1299 }
  ];

  return (
    <div style={{ maxWidth: "600px", margin: "30px auto", padding: "20px", background: "#f8fafc", borderRadius: "16px" }}>
      <h2 style={{ color: "#002057" }}>Lecture 6: Conditional Rendering Masterclass</h2>

      {/* Control Buttons */}
      <div style={{ display: "flex", gap: "8px", marginBottom: "20px" }}>
        <button onClick={() => setViewState('loading')}>Simulate Loading</button>
        <button onClick={() => setViewState('error')}>Simulate Error</button>
        <button onClick={() => setViewState('empty')}>Simulate Empty</button>
        <button onClick={() => setViewState('success')}>Simulate Success</button>
      </div>

      {/* Dynamic Conditional Rendering */}
      {viewState === 'loading' && (
        <div style={{ padding: "30px", background: "#e0f2fe", color: "#0369a1", borderRadius: "10px", textAlign: "center" }}>
          <h3>โณ Loading Data from API...</h3>
          <p>Please wait while we fetch the latest records.</p>
        </div>
      )}

      {viewState === 'error' && (
        <div style={{ padding: "20px", background: "#fef2f2", color: "#991b1b", borderRadius: "10px" }}>
          <h3>โŒ Connection Failed!</h3>
          <p>Unable to connect to server. Please try again later.</p>
        </div>
      )}

      {viewState === 'empty' && (
        <div style={{ padding: "30px", background: "#fef3c7", color: "#92400e", borderRadius: "10px", textAlign: "center" }}>
          <h3>๐Ÿ“ญ No Items Found</h3>
          <p>Your shopping cart is currently empty.</p>
        </div>
      )}

      {viewState === 'success' && (
        <div style={{ padding: "20px", background: "#f0fdf4", border: "1px solid #bbf7d0", borderRadius: "10px" }}>
          <h3 style={{ color: "#166534" }}>๐Ÿ›’ Product Catalog ({sampleProducts.length} Items)</h3>
          <ul>
            {sampleProducts.map(p => (
              <li key={p.id}>{p.name} โ€” โ‚น{p.price}</li>
            ))}
          </ul>
        </div>
      )}
    </div>
  );
}