React Conditional Rendering

Master the core techniques for creating dynamic and responsive UIs. Learn to show, hide, and switch components based on state and props.

Lesson ProgressStep 1 of 10

Welcome Back!

Here is your dashboard.

3

0

Hello, Guest!

0 EXP

Welcome! Let's make our React components smart enough to change what they display based on data.

// We start with a simple state
const [isLoggedIn, setIsLoggedIn] = useState(false);

The Ternary Operator (`? :`)

This is your primary tool for a simple `if...else` choice directly inside your JSX. Because it's a JavaScript **expression** (it returns a value), it's allowed inside the ``.

The syntax is: condition ? expressionIfTrue : expressionIfFalse.

return (
  <p>{isOnline ? 'Online' : 'Offline'}</p>
);

It's perfect for swapping between two components, values, or class names.

System Check

Why can't you use a standard 'if...else' statement inside JSX curly braces {}?

Advanced Holo-Simulations

0 EXP

Log in to unlock these advanced training modules and test your skills.


Achievements

🏆
Ternary Master

Use the ternary operator to render one of two components.

🏗️
Short-Circuit Whiz

Correctly use && to render an element conditionally.

✍️
Dynamic UI Expert

Combine state and conditional logic to build a dynamic UI.

Mission: Render a Notification

Edit the `Notification` component. It should render a `<div>` with the message count **only if** `unreadMessages > 0`. Otherwise, it must render `null`.

A.D.A. Feedback:

> System integrity looks stable. Code is valid.

Challenge: Match the Operator to the Use Case

Drag the code examples on the left to match the correct use case on the right.

Logical AND (&&)

`{ isLoggedIn && <Dashboard /> }`

Ternary Operator (? :)

`{ isLoading ? <Spinner /> : <Content /> }`

Logical OR (||)

`{ userName || 'Guest' }`
Use Case: Choosing between two distinct components.
Use Case: Rendering a component *only if* a condition is true.
Use Case: Providing a fallback value if data is falsy.

Challenge: Complete the Syntax

Fill in the missing operators to build a dynamic UI.

function UserProfile({ user, isLoading }) {
if (isLoading) {
return <Spinner />;
}
return (
<div>
<h1>{user.name 'Welcome' : 'Please Log In'}</h1>
{user.isAdmin <AdminPanel />}
</div>
);
}

Let's simplify. Complete this snippet:

{isLoggedIn <p>Welcome</p> <p>Guest</p> }
{hasPermission <EditButton /> }

Consult A.D.A.

Community Holo-Net

Peer Project Review

Submit your "Dynamic UI" component for feedback from other Net-Runners.

Dynamic UIs: A Deep Dive into React's Conditional Rendering

In React, building a static website is only half the story. The true power of React is in building **dynamic user interfaces** that respond to state, props, and user interactions. The core technique behind this is **conditional rendering**.

Conditional rendering is exactly what it sounds like: a way to render specific JSX elements or components **only if** certain conditions are met. React leverages standard JavaScript logic, but there are specific patterns that are essential to master.

Pattern 1: `if` Statements (Element Variables)

You **cannot** use a standard `if...else` statement directly inside JSX curly braces ``. JSX is just syntactic sugar for function calls, and `if` statements are not valid JavaScript expressions (they don't return a value).

The solution is to use an `if` statement *before* the `return` statement to assign JSX to a variable. This is known as the "element variable" pattern and is excellent for complex logic.

function Greeting({ isLoggedIn }) {
  let content; // This is our element variable

  if (isLoggedIn) {
    content = <Dashboard />;
  } else {
    content = <LoginPage />;
  }

  return (
    <div>
      {content} {/* Render the variable here */}
    </div>
  );
}

Pattern 2: The Ternary Operator (`? :`)

This is the most common and concise way to handle a simple `if-else` condition *inside* your JSX. The ternary operator **is** a JavaScript expression, so it's perfectly valid.

function Greeting({ isLoggedIn }) {
  return (
    <div>
      {isLoggedIn ? <Dashboard /> : <LoginPage />}
    </div>
  );
}

You can even use it for simple text: {isOnline ? 'Online' : 'Offline'}. While you can nest ternaries, it's strongly discouraged as it quickly becomes unreadable. For nested logic, use element variables.

Pattern 3: Logical AND (`&&`) - Short-Circuiting

What if you want to render something *or nothing*? You could use a ternary (`condition ? <Component /> : null`), but a more elegant way is to use the logical AND (`&&`) operator.

In JavaScript, `true && expression` always evaluates to `expression`, and `false && expression` always evaluates to `false`. React knows not to render `false`, `null`, or `undefined`.

function Mailbox({ unreadMessages }) {
  return (
    <div>
      <h1>Hello!</h1>
      {unreadMessages.length > 0 &&
        <h2>
          You have {unreadMessages.length} unread messages.
        </h2>
      }
    </div>
  );
}

Common Pitfall: The `0` Problem with `&&`

There is a major "gotcha" with `&&`. What if your condition evaluates to the number `0`?

`0` is a **falsy** value. So `0 && <Component />` will short-circuit and evaluate to `0`. The problem? Unlike `false` or `null`, **React renders the number 0**!

❌ Bad Practice

const count = 0;
{count && <Messages />}
// Renders: 0

This will display a "0" on your page.

✔️ Good Practice

const count = 0;
{count > 0 && <Messages />}
// Renders: (nothing)

This expression is a true boolean (`false`), so React renders nothing.

**Always ensure the left side of `&&` is a true boolean (true/false).**

Pattern 4: Logical OR (`||`) - Fallback Values

The logical OR (`||`) operator is perfect for providing default or fallback values. `a || b` will return `a` if it's "truthy," otherwise it will return `b`.

// If user.name is null or an empty string, it will show 'Guest'
<h1>Hello, {user.name || 'Guest'}</h1>
Key Takeaway: Choose the right tool for the job. Use **element variables** for complex logic, the **ternary operator (`? :`)** for simple A/B choices, and **`&&`** (with a boolean check!) for "render or nothing" logic.

React Conditional Rendering Glossary

Conditional Rendering
The practice in React of outputting different JSX based on certain conditions (e.g., state or props), allowing for dynamic UIs.
JSX
JavaScript XML. A syntax extension for JavaScript that lets you write HTML-like structures in your React code. You can embed JavaScript expressions (like ternaries) inside JSX with curly braces ``.
Ternary Operator (`? :`)
A JavaScript expression (and the only way to do inline `if-else` in JSX). Syntax: `condition ? expressionIfTrue : expressionIfFalse`.
Logical AND (`&&`)
Used for "short-circuiting." In `a && b`, if `a` is falsy, it returns `a`. If `a` is truthy, it returns `b`. In React, `condition && <Component />` renders the component only if the condition is truthy.
Logical OR (`||`)
Also a short-circuit operator. In `a || b`, if `a` is truthy, it returns `a`. If `a` is falsy, it returns `b`. Used in React to provide fallback values (e.g., `props.name || 'Guest'`).
Truthy
A value that is considered `true` when evaluated in a boolean context. Examples: `true`, any number except `0`, non-empty strings (`"hello"`), objects (``), arrays (`[]`).
Falsy
A value that is considered `false` when evaluated in a boolean context. There are only six: `false`, `0`, `""` (empty string), `null`, `undefined`, and `NaN`.
Element Variable
A pattern where you declare a variable (e.g., `let content;`) before the `return` statement, use standard `if...else` logic to assign JSX to it, and then render that variable inside the return: `{content}`.

About the Author

Author's Avatar

TodoTutorial Team

Passionate developers and educators making programming accessible to everyone.

This article was written and reviewed by our team of senior React developers, who use conditional rendering daily to build robust, enterprise-scale applications.

Verification and Updates

Last reviewed: October 2025.

We strive to keep our content accurate and up-to-date. This tutorial is based on the latest React (v18+) documentation and is periodically reviewed to reflect industry best practices.

External Resources

Found an error or have a suggestion? Contact us!