← Back to Chapters

If-Else Rendering

⚛️ If-Else Rendering

✨ Conditional UI ? Multiple States ? Readable Logic

⚡ Quick Overview

One of the most common techniques in React is if-else rendering, where different JSX blocks are rendered based on a condition. It is particularly useful when your component needs to switch between two or more completely different UI states.

Think of it as: “If a user is logged in, show the dashboard — else, show the login screen.”

In this topic, you will learn how to:

  • Use basic if-else statements to return different JSX.
  • Store JSX in variables before returning it.
  • Handle multiple UI states using if-else chains.
  • Extract conditional logic into helper functions.

? Key Concepts

  • If-Else Before Return: Decide what to render before the return statement.
  • JSX in Variables: Store JSX in variables like message and return them later.
  • Chained Conditions: Use if / else if / else to manage multiple UI states.
  • Helper Functions: Move complex conditional logic into separate functions for clarity.
  • No If-Else Inside JSX: JSX is an expression; you cannot directly put an if statement inside it.
  • Return null: Use null when you want to render nothing for a condition.

? Syntax & Theory

In React, if-else rendering means using regular JavaScript control flow to decide which JSX tree a component should return.

General pattern:

? View Code Example
// Decide which JSX to return using if-else
function Example({ condition }) {
  if (condition) {
    return <p>Condition is true ✅</p>;
  } else {
    return <p>Condition is false ❌</p>;
  }
}

Notice that the if runs before React renders anything. Only one branch’s JSX is returned and rendered.

? Code Examples

? Basic if-else Example

Use a simple if-else statement before the return to determine which JSX element should be rendered.

? View Code Example
// Renders a different message based on login status
function LoginStatus({ isLoggedIn }) {
  if (isLoggedIn) {
    return <h4>Welcome back, User! ?</h4>;
  } else {
    return <h4>Please log in to continue.</h4>;
  }
}

The component checks the isLoggedIn prop and conditionally renders one of two messages.

? if-else with Variables

Sometimes, you may want to determine what to render by assigning JSX to a variable first and returning it later. This improves readability in more complex conditions.

? View Code Example
// Store JSX in a variable and return it at the end
function UserGreeting({ isAdmin }) {
  let message;

  if (isAdmin) {
    message = <h4 className="text-success">Welcome, Admin!</h4>;
  } else {
    message = <h4 className="text-primary">Welcome, User!</h4>;
  }

  return <div>{message}</div>;
}

Here, JSX is stored in the message variable and rendered once at the end, making it easier to handle larger logic branches.

? Multiple if-else Chains

Use chained conditions when you have more than two UI states.

? View Code Example
// Display different messages for loading, error, or success
function StatusMessage({ status }) {
  if (status === "loading") {
    return <p className="text-warning">Loading data...⏳</p>;
  } else if (status === "error") {
    return <p className="text-danger">Error loading data! ❌</p>;
  } else {
    return <p className="text-success">Data loaded successfully! ✅</p>;
  }
}

This pattern is clear and expressive, especially when you have distinct UI sections for different conditions.

? Using Helper Functions for Readability

When conditions get too complex, move the logic into a helper function for better clarity.

? View Code Example
// Extract conditional logic into a reusable helper
function getMessage(status) {
  if (status === "success") return "✅ Success!";
  if (status === "error") return "❌ Failed!";
  return "⏳ Loading...";
}

function Status({ status }) {
  return <h4>{getMessage(status)}</h4>;
}

Extracting conditional logic makes your JSX cleaner and improves testability.

⚙️ Inline vs External if-else

You can’t directly use if-else inside JSX (because JSX is an expression), but you can evaluate the condition before returning JSX or use ternary operators for inline conditions.

? View Code Example
// Demonstrates invalid and valid ways to use if-else with JSX
// ❌ Invalid (cannot use if-else directly inside JSX)
return (
  <div>
    { if (isLoggedIn) { <h4>Hi!</h4> } else { <h4>Bye!</h4> } }
  </div>
);

// ✅ Correct - condition evaluated before return
if (isLoggedIn) {
  return <h4>Hi!</h4>;
}
return <h4>Bye!</h4>;

? Practical Example: Dashboard

A common real-world scenario: show a login button when the user is logged out, and a dashboard when they are logged in.

? View Code Example
// Switch between login button and dashboard using if-else
function Dashboard({ isLoggedIn, name }) {
  if (!isLoggedIn) {
    return <button className="btn btn-primary">Login</button>;
  }

  return (
    <div className="p-3 border rounded">
      <h4>Welcome, {name}!</h4>
      <p>You are now inside your dashboard.</p>
      <button className="btn btn-danger">Logout</button>
    </div>
  );
}

?️ Live Output & Explanation

? How React Chooses What to Render

Imagine calling the StatusMessage component with different status values:

  • <StatusMessage status="loading" />“Loading data...⏳”
  • <StatusMessage status="error" />“Error loading data! ❌”
  • <StatusMessage status="success" />“Data loaded successfully! ✅”

Only one branch runs each time the component renders. React simply takes the returned JSX from that branch and updates the UI accordingly.

This makes if-else rendering perfect for:

  • Login / logout flows.
  • Loading, success, and error states.
  • Feature flags or role-based UIs (admin vs normal user).

? Tips & Best Practices

  • Use if-else outside JSX for cleaner code and better debugging.
  • Use variables or helper functions for multiple conditional outputs.
  • Return null when you don’t want to render anything for a condition.
  • For short conditions, prefer the ternary (? :) operator instead.
  • Keep each branch’s JSX focused and small to improve readability.

? Try It Yourself / Practice Tasks

  1. Build a LoginStatus component that shows “Login” or “Logout” buttons using if-else.
  2. Create a StatusMessage component with “loading”, “error”, and “success” states.
  3. Refactor your component to move conditional logic into a helper function like getMessage().
  4. Experiment with returning null for a hidden UI state (e.g., hide a banner after a user closes it).

Goal: Learn how to render different UI sections using if-else logic in React for clear, readable, and maintainable component behavior.