Conditional Rendering in React

Master the art of creating dynamic and responsive UIs by telling your components what to render, and when.

Lesson ProgressStep 1 of 9
isLoggedIn: false

Please Login

0 EXP

Welcome! Let's learn how React decides what to show on the screen. It all starts with state.

// We need a way to store data that changes...

The Ternary Operator: An If/Else in JSX

Since you can't write `if/else` statements directly in JSX, the ternary operator is your main tool for choosing between **two** different renders. The syntax is condition ? expressionIfTrue : expressionIfFalse.

function Greeting({ isLoggedIn }) {
  return (
    <h1>
      {isLoggedIn ? 'Welcome back!' : 'Please sign in.'}
    </h1>
  );
}

This is clean, concise, and works perfectly inside the `` braces.

System Check

What is the correct syntax for a ternary operator?

Advanced Holo-Simulations

0 EXP

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


Achievements

Ternary Master

Correctly use the ternary operator to render one of two components.

Short-Circuit Pro

Use the && operator to conditionally render an element.

🏗️
Dynamic UI Architect

Combine state and conditional logic to build a responsive component.

Mission: Build a Dynamic Component

Create a component `UserGreeting` that takes an `isLoggedIn` prop. If `isLoggedIn` is true, render `

Welcome back!

`. If false, render `

Please sign in.

`.

A.D.A. Feedback:

> System integrity looks stable. Code is valid.

Challenge: Order the Component Logic

A component's structure matters. Drag the code blocks into the correct logical order from top to bottom.

{data ? <Component /> : <Loading />}
const [data, setData] = useState(null);
return <div>...</div>

Challenge: Complete the Syntax

Fill in the missing parts to render a notification count only if it's greater than 0.

function Notifications( { count } ) { return (<>{(count > 0)<p>You have {count} messages.</p>}{(count === 0)<p>No new messages.</p>}</>)}

Consult A.D.A.

Community Holo-Net

Peer Project Review

Submit your "Dynamic Component" project for feedback from other Net-Runners.

Beyond True and False: The Power of Conditional Rendering in React

In React, you don't just build static UIs; you build dynamic systems that respond to data. **Conditional rendering** is the set of techniques you use to decide *what* to show the user. It's not one single feature but a combination of JavaScript's logical operators used inside your JSX.

The `if/else` Statement (And Why It Doesn't Work in JSX)

Your first instinct might be to use a standard `if` statement. But if you try this, your code will break:

// ❌ This code will NOT work!
return (
  <div>
    if (isLoggedIn) {
      <UserProfile />
    } else {
      <LoginForm />
    }
  </div>
)

This fails because JSX curly braces `` can only contain **expressions** (things that evaluate to a value, like `1 + 1` or `user.name`), not **statements** (multi-line instructions like `if`, `for`, `switch`).

You *can* use `if/else` *before* the `return` statement to prepare variables, but a more direct approach is to use JavaScript expressions that *do* fit inside ``.

Tool 1: The Ternary Operator (`? :`) - The A/B Switch

This is the most common and direct replacement for an `if/else` block. It's an expression, so it works perfectly inside JSX.

return (
  <div>
    {isLoggedIn ? <UserProfile /> : <LoginForm />}
  </div>
)

Use this when you have **two distinct outcomes**: render A or render B.

Tool 2: Logical AND (`&&`) - The "Render or Nothing" Shortcut

Often, you don't have an "else" condition. You just want to show a component *if* a condition is true, and show *nothing* otherwise. This is where `&&` shines.

return (
  <div>
    {unreadMessages > 0 && <NotificationBell count={unreadMessages} />}
  </div>
)

This works because of "short-circuiting." If `unreadMessages > 0` is `false`, JavaScript doesn't even look at the part after `&&` and just returns `false`. React knows to render nothing for `false`. If it's `true`, JavaScript moves to the part after `&&` and returns the `NotificationBell` element, which React then renders.

The Critical Pitfall of `&&`: The '0' Bug

There's a major "gotcha" with `&&`. What if `unreadMessages` is `0`?

❌ Bad Practice

{unreadMessages && <NotificationBell />}
// If unreadMessages is 0...

...JavaScript evaluates `0 && ...`, which short-circuits to `0`. React **will render the `0`** to the screen! Your user will see a "0" on the page.

✔️ Good Practice

{unreadMessages > 0 && <NotificationBell />}
// or...
{Boolean(unreadMessages) && <NotificationBell />}

By converting the number to a true boolean (`true` or `false`), you avoid the bug. `false` renders nothing, which is what you want.

Tool 3: Logical OR (`||`) & Coalescing (`??`) - The Fallbacks

These operators are perfect for providing default values.

  • Logical OR (`||`): Returns the right-hand side if the left side is any **falsy** value (`0`, `""`, `false`, `null`, `undefined`).
    {username || 'Guest'} (If `username` is `""`, it shows 'Guest')
  • Nullish Coalescing (`??`): This is a newer, often safer, alternative. It *only* returns the right-hand side if the left side is `null` or `undefined`.
    {score ?? 0} (If `score` is `0`, it will correctly show `0`, not the fallback. `||` would incorrectly show the fallback.)
Key Takeaway: Always choose the right tool for the job.
• **Ternary (`? :`)** for A-or-B logic.
• **`&&`** for A-or-Nothing logic (and be careful of `0`!).
• **`??` or `||`** for providing fallback values.

React Conditional Rendering Glossary

Conditional Rendering
The practice of rendering different UI elements or components based on the current state or props.
JSX Expression (``)
The curly braces used in JSX to embed JavaScript logic and variables. Only "expressions" (which return a value) are allowed, not "statements" (like `if/else` blocks).
Ternary Operator (`? :`)
A JavaScript expression that provides a compact `if/else` replacement. Syntax: `condition ? expressionIfTrue : expressionIfFalse`.
Short-Circuit Evaluation
The behavior of `&&` and `||` operators. JavaScript stops evaluating as soon as it knows the final result. In React, `false && <Component />` evaluates to `false` (renders nothing).
Logical AND (`&&`)
Used in React to render a component *only if* a condition is true. Example: `isLoggedIn && <Dashboard />`.
Falsy Values
Values that JavaScript considers "false" in a boolean context. They are: `false`, `0`, `""` (empty string), `null`, `undefined`, and `NaN`. This is crucial for the `&&` pitfall, as `0 && ...` evaluates to `0`.
Logical OR (`||`)
Used to provide a fallback value if the first value is **falsy**. Example: `username || 'Guest'`.
Nullish Coalescing Operator (`??`)
A safer alternative to `||`. It provides a fallback *only if* the first value is `null` or `undefined`. It will *not* trigger for `0` or `""`.
Rendering `null`
The practice of explicitly returning `null` from a component's render method (or as part of a ternary) to render nothing. React knows not to render anything for `null`.

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 web development experts, who have years of experience teaching React and building robust and accessible web 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 specifications (v18+) and is periodically reviewed to reflect industry best practices.

External Resources

Found an error or have a suggestion? Contact us!