← Back to Chapters

Conditional Rendering

⚛️ Conditional Rendering

? Quick Overview

Conditional rendering in React means showing different UI based on conditions — just like using if, ?: (ternary), or && in JavaScript. It lets you display or hide components based on state, props, or any logic in your app.

Example: show a “Login” button when the user is logged out and a “Logout” button when they are logged in.

? Key Concepts

  • if / else — clear and explicit branching logic.
  • Ternary ? : — short inline condition inside JSX.
  • Logical AND && — render something only when a condition is true.
  • Inline functions — handle more complex logic inside JSX.
  • Component-level conditions — swap whole components based on roles or state.
  • Multiple conditions — nested ternaries or extracted helper functions.

? Syntax & Theory

React doesn’t have a special “conditional rendering” syntax. Instead, it uses normal JavaScript expressions inside JSX:

  • if / else: decide which element to return from a component.
  • Ternary: inline choice between two UI fragments.
  • && operator: render something only if a condition is truthy.
  • Return null: to render nothing when a condition fails.

? Code Examples

1️⃣ Using if Statements

Use regular if conditions inside the component body to choose what to return.

? View Code Example (if / else)
// Using if...else to show different greetings
function UserGreeting({ isLoggedIn }) {
  if (isLoggedIn) {
    return <h4>Welcome back, User!</h4>;
  } else {
    return <h4>Please log in.</h4>;
  }
}

// Usage:
<UserGreeting isLoggedIn={true} />

2️⃣ Using the Ternary Operator

For simple either/or UI, the ternary operator keeps JSX compact and readable.

? View Code Example (Ternary)
// Using a ternary to choose between morning and evening text
function Greeting({ isMorning }) {
  return (
    <h4>
      {isMorning ? "Good Morning ☀️" : "Good Evening ?"}
    </h4>
  );
}

3️⃣ Using Logical AND (&&)

Render something only when a condition is true. If it’s false, React ignores the element.

? View Code Example (&&)
// Only show the message if hasMessage is true
function Notification({ hasMessage }) {
  return (
    <div>
      {hasMessage && <p>You have a new message!</p>}
    </div>
  );
}

4️⃣ Using Inline Functions for Complex Logic

For multiple branches in a small area, an immediately invoked function expression (IIFE) can keep logic close to the JSX.

? View Code Example (Inline Function)
// Use an inline function to handle multiple status states
function StatusMessage({ status }) {
  return (
    <div>
      {(() => {
        if (status === "loading") return <p>Loading...⏳</p>;
        if (status === "error") return <p>❌ Something went wrong!</p>;
        return <p>✅ Data loaded successfully!</p>;
      })()}
    </div>
  );
}

5️⃣ Conditional Rendering with Components

Often you conditionally render entire components instead of small elements.

? View Code Example (Components)
// Swap between Admin and User dashboards based on isAdmin
function AdminPanel() {
  return <h5>Admin Dashboard</h5>;
}

function UserPanel() {
  return <h5>User Dashboard</h5>;
}

function Dashboard({ isAdmin }) {
  return (
    <div>
      {isAdmin ? <AdminPanel /> : <UserPanel />}
    </div>
  );
}

6️⃣ Combining Multiple Conditions

For more than two options, you can chain ternaries — but keep an eye on readability.

? View Code Example (Multiple Conditions)
// Choose a different message based on the temperature
function Weather({ temp }) {
  return (
    <p>
      {temp > 30
        ? "It's hot ?"
        : temp > 20
        ? "Nice and warm ?️"
        : "Cold day ❄️"}
    </p>
  );
}

? Live Output / Explanation

What the user sees

  • <UserGreeting isLoggedIn={true} />“Welcome back, User!”
  • <Greeting isMorning={false} />“Good Evening ?”
  • <Notification hasMessage={false} />No message line rendered at all
  • <Weather temp={25} />“Nice and warm ?️”

Notice that when a condition is false (like hasMessage), React simply renders nothing for that expression — it doesn’t leave a blank hole on the screen.

? Tips & Best Practices

  • Prefer ternary or && for short, readable conditions.
  • Use if statements when logic is complex or has multiple branches.
  • Extract long conditional expressions into helper functions or separate components.
  • Return null from a component to render nothing when a section should be hidden.
  • Avoid deeply nested ternaries — they become hard to read and maintain.

? Try It Yourself

  1. Create a component that shows “Welcome User” only if isLoggedIn is true.
  2. Show different emoji icons based on temperature using nested ternaries.
  3. Use && to display a message when a list is empty.
  4. Build a “Theme Switcher” component that shows either a dark or light theme card based on a boolean value.

Goal: Learn how to render UI elements dynamically using different conditional rendering patterns for clean and responsive React components.