Thuta Learning
React
BasicWeb DevelopmentIntermediate

Conditional Rendering

ReactLesson 920 min

What you'll walk away with

  • Use if with an early return before the JSX for states like loading and error
  • Choose a ternary for either/or UI and && for show-or-nothing UI
  • Explain and fix the bug where {count && ...} prints 0 on screen
  • Know that null, false and undefined render nothing while 0 and strings do render

Explain it simply

Explain it simply

Picture a sign at a library entrance. During opening hours it says "Welcome"; after hours it says "Closed, come back at 9". The sign is the same object; only the message changes with the condition, the time of day.

React components work the same way. A component looks at its props and state and decides which JSX to return. No special React syntax is needed for this: you use JavaScript's own if, ? : and &&.

Problem → Why → Solution

The problem: a stray 0 next to the inbox

You want a badge only when there are unread messages, so you write the code below. It works while messages exist, but when unread drops to 0 the badge does not simply vanish: a lone "0" appears next to Inbox. On a mobile layout that stray digit even pushes the icons out of place.

InboxLink.jsx
function InboxLink({ unread }) {
  return (
    <a href="/inbox">
      Inbox
      {unread && <span className="badge">{unread}</span>}
    </a>
  );
}

// <InboxLink unread={0} />  renders: <a href="/inbox">Inbox0</a>

Why does 0 show up?

JavaScript's a && b returns a itself when a is falsy, without looking at b. With unread equal to 0, the whole expression evaluates to 0, and React renders numbers as text. Only false, null and undefined render nothing. Writing {unread > 0 && ...} turns the left side into a real boolean and fixes it.

Core concept: choose JSX with plain JavaScript

Only expressions are allowed inside JSX braces, not statements like if. That leaves four techniques for conditional rendering. The first is an if with an early return before the JSX: write if (isLoading) return <Spinner />; and the rest of the component only has to think about the not-loading case. For states that replace the whole screen, such as loading, error or no permission, this is the clearest choice.

The second is the ternary operator, condition ? A : B. It fits in the middle of JSX when you need one of two things, such as "Log out" when signed in and "Log in" otherwise. The third is condition && A, for "show this or nothing". Always make the left side of && a real boolean (count > 0, items.length > 0, Boolean(user)), or you will meet the 0 bug above again.

The fourth is storing JSX in a variable: let content = <Empty />; if (items.length) content = <List items={items} />; and then put {content} in the return. When ternaries start nesting inside each other and become hard to read, this shape is much clearer.

You also need to know how React treats each kind of value. null, undefined, true and false render nothing. Strings and numbers, including 0 and NaN, appear as text. To make a whole component render nothing, return null; that said, it is usually more natural for the parent to decide with {show && <Panel />}.

One last point: a condition also affects component state. In {show && <Panel />}, when show turns false React removes Panel from the tree (unmounts it) and all of its state is lost; when it comes back, it starts fresh. Hiding it with CSS keeps the component in the tree, so its state survives.

Mental model: a decision before the drawing
  1. Read props and state
  2. Whole screen differs: early return
  3. One part differs: ? : or &&
  4. Return the remaining JSX

The left side of && must be a boolean, never a bare number.

General pattern

jsx
function Component({ status, flag, count }) {
  if (status === 'loading') return <Fallback />;   // whole screen
  if (status === 'hidden') return null;             // render nothing
  return (
    <Wrapper>
      {/* either / or */}
      {flag ? <OptionA /> : <OptionB />}
      {/* show or nothing */}
      {count > 0 && <Extra count={count} />}
    </Wrapper>
  );
}

Handle whole-screen states at the top with early returns. Inside the JSX, use ? : for either/or and a boolean && for show-or-nothing.

Example: a greeting that depends on login

The Greeting component looks at its isLoggedIn prop and uses a ternary to pick one of two headings. App passes isLoggedIn={true}, so the welcome heading appears.

jsx
function Greeting({ isLoggedIn, userName }) {
  return (
    <div>
      {isLoggedIn ? (
        <h1>Welcome back, {userName}!</h1>
      ) : (
        <h1>Please sign in to continue.</h1>
      )}
    </div>
  );
}

function App() {
  return <Greeting isLoggedIn={true} userName="Sai" />;
}

Code breakdown

  1. Line 1function Greeting({ isLoggedIn, userName }) {

    The condition arrives as a prop. Greeting does not know how login works; it only reacts to the value it receives, which makes it easy to test.

  2. Line 4{isLoggedIn ? (

    Braces only accept expressions, so a ternary stands in for if. When isLoggedIn is true, the JSX after ? is used.

  3. Line 6) : (

    The part after : is the JSX for the false case. Both branches are an <h1>, so the layout stays stable and only the text changes.

  4. Line 14return <Greeting isLoggedIn={true} userName="Sai" />;

    Change it to isLoggedIn={false} and "Please sign in to continue." appears instead; userName is no longer used.

You should see
One heading appears: Welcome back, Sai!
(Rendered HTML: <div><h1>Welcome back, Sai!</h1></div>)

Which technique to use when

TechniqueUse it whenWatch out for
if + early returnThe whole screen is replaced (loading, error)Call all Hooks before the first return
cond ? A : BExactly one of two thingsNested ternaries get unreadable
cond && AShow something or nothingA 0 on the left is rendered
JSX variableThree or more casesAssign the variable in one place

Early returns and Hooks

Calling a Hook like useState or useEffect below an if (loading) return ... changes the number of Hooks between renders, and React throws an error. Call every Hook at the top of the component, then do the early returns.

In real projects

Where this shows up in real projects

Every screen that loads data from a server has four states: loading, error, empty and ready. Production apps design UI for all four: a skeleton while loading, a message with a "Try again" button on error, and an "No orders yet" panel with a link to place a first order when empty. Writing only the happy path and forgetting the rest is the main reason users stare at blank screens.

Permission-based UI is just as common: {user.role === 'admin' && <DeleteButton />}. Hiding a button is not security, though; the server must check permissions again. Feature flags, which show a new feature to only some users, and some responsive layouts are built from these same conditional rendering patterns.

Common mistakes

Common mistakes

1. A number on the left of &&

{items.length && <List />} prints 0 when the array is empty. Write {items.length > 0 && <List />}, or use a ternary that shows a proper empty state instead.

2. Trying to write if inside JSX

<div>{if (ok) { <p>Yes</p> }}</div> is a syntax error, because braces cannot hold statements. Move the if above the return, or use a ternary or &&.

3. Stacking ternaries three deep

Code like a ? <A /> : b ? <B /> : c ? <C /> : <D /> makes it hard to see which condition leads to which UI. With more than two cases, use early returns or a JSX variable, or split each case into its own component.

Best practices

Best practices

  • When a condition grows long, move it out of the JSX into a well-named variable such as const canCheckout = items.length > 0 && !isLocked;.
  • For every new data-driven component, go through loading, error, empty and ready as a checklist and look at each one.
  • Consider a skeleton of the same size instead of a spinner, so the layout does not jump when loading finishes.
  • When a branch gets long, extract it into its own component like <EmptyCart /> and let the parent only decide which one to show.

Mini challenge

Mini challenge: four cart states

Write a CartSummary component that takes status, items and error props and renders all four states correctly: loading, error, empty and ready.

  • Handle loading and error with early returns before the JSX
  • Use a ternary to show "Your cart is empty." or the number of items
  • Show "Bulk discount: 10%" only for three or more items, and never print a stray 0
  • Show the Checkout button only when there are items
CartSummary.jsx
function CartSummary({ status, items, error }) {
  // TODO: early return for 'loading'
  // TODO: early return for 'error' (show the error text)

  return (
    <section>
      <h2>Your cart</h2>
      {/* TODO: empty message OR "N item(s) in your cart" */}
      {/* TODO: bulk discount line for 3+ items */}
      {/* TODO: Checkout button only when there are items */}
    </section>
  );
}

export default function App() {
  // TODO: render one CartSummary for each of the four states
}

Expected: Loading your cart... Could not load the cart: Network timeout Your cart / Your cart is empty. (no button) Your cart / 3 item(s) in your cart / Bulk discount: 10% / Checkout button

Show hint

Compute const discount = count >= 3 ? 10 : 0; and test {discount > 0 && ...}. Writing {discount && ...} would print 0 for small carts.

Show solution
CartSummary.jsx
function CartSummary({ status, items, error }) {
  if (status === 'loading') {
    return <p>Loading your cart...</p>;
  }
  if (status === 'error') {
    return <p role="alert">Could not load the cart: {error}</p>;
  }

  const count = items.length;
  const discount = count >= 3 ? 10 : 0;

  return (
    <section>
      <h2>Your cart</h2>
      {count === 0 ? <p>Your cart is empty.</p> : <p>{count} item(s) in your cart</p>}
      {discount > 0 && <p>Bulk discount: {discount}%</p>}
      {count > 0 && <button type="button">Checkout</button>}
    </section>
  );
}

export default function App() {
  return (
    <>
      <CartSummary status="loading" />
      <CartSummary status="error" error="Network timeout" />
      <CartSummary status="ready" items={[]} />
      <CartSummary status="ready" items={['pen', 'book', 'bag']} />
    </>
  );
}

Quick quiz 1 / 3

With const count = 0;, what does <div>{count && <p>New!</p>}</div> render?

Quick quiz 2 / 3

Which expression shows a badge only when unread > 0 and never prints a stray character?

Quick quiz 3 / 3

While data is loading you want only a spinner and none of the rest of the UI. Which approach is clearest?

What to remember

  • Conditional rendering is plain JavaScript: if with early return, ? :, && and JSX variables.
  • Use an early return when the whole screen changes, a ternary for either/or, and && for show-or-nothing.
  • null, undefined, true and false render nothing, but 0 and NaN render as text, so keep the left side of && boolean.
  • Call Hooks before any early return, and design all four states: loading, error, empty and ready.

React Documentation — React

Updated on

Progress is saved only in this browser on this device. It isn't synced to other devices.

Report a problem with this lessonOpens your email app with this lesson's address filled in — nothing is sent until you send it.

Conditional Rendering | Thuta Learning