iwantcoding.com
🔥 Daily 👥 Rooms 🏆 Top Log in Sign up

Conditional Rendering

Conditional rendering in React: ternaries, short-circuit, early returns, and the patterns that scale across components.

React — conditional rendering

EXAMPLE
// ===== Short-circuit (&&) =====
function Badge({ user }) {
  return (
    <div>
      <span>{user.name}</span>
      {user.isAdmin && <em> (admin)</em>}
    </div>
  );
}

// CAREFUL: && returns 0 or '' for falsy non-boolean values:
// {items.length && <List />}  -> renders '0' when empty!
// Use a real boolean: {items.length > 0 && <List />}

// ===== Ternary (a ? b : c) =====
function Greeting({ user }) {
  return <h1>{user ? \`Hello, ${user.name}\` : 'Sign in'}</h1>;
}

// ===== Multiple branches =====
function Status({ value }) {
  if (value === 'loading') return <Spinner />;
  if (value === 'error')   return <ErrorMessage />;
  return <Content />;
}
// Early returns read cleaner than nested ternaries.

// ===== Object/Map lookup =====
const ICONS = { warning: <WarnIcon />, error: <ErrorIcon />, info: <InfoIcon /> };
function Toast({ kind }) {
  return <div>{ICONS[kind] ?? null}<span>...</span></div>;
}

// ===== Hide vs unmount =====
// Conditional render REMOVES the component (state resets).
{isOpen && <Modal />}
// CSS hide keeps state but reserves space:
<Modal style={{ display: isOpen ? 'block' : 'none' }} />

// Pick based on whether state should persist across toggle.

// ===== Avoiding deeply nested ternaries =====
// Hard to read:
return cond1 ? (cond2 ? <A /> : <B />) : (cond3 ? <C /> : <D />);

// Better: extract or use early returns
if (!cond1) return cond3 ? <C /> : <D />;
return cond2 ? <A /> : <B />;

// ===== Component-level switch =====
function View({ mode }) {
  switch (mode) {
    case 'list':   return <List />;
    case 'grid':   return <Grid />;
    case 'detail': return <Detail />;
    default:       return null;
  }
}

// ===== Patterns to internalise =====
// - && for one branch, ternary for two, early return for three+
// - Hide vs unmount based on whether state must persist
// - Extract sub-views once a render has 3+ conditionals
// - Map of components for finite enum-like states

// ===== Pitfalls =====
// - && with a number: 0 renders, empty string renders nothing
// - Nested ternaries past 2 levels -> illegible
// - Re-creating children on every render in inline objects/arrays
// - Conditionally hooking calls (rules of hooks!)

Why it matters

Conditional rendering is mostly about choosing the right operator for the branch count. && for one, ternary for two, early return or component-level switch for three or more. Hide vs unmount changes state lifetime — pick deliberately.

Tip: Tweak the snippet with Try it Yourself », then sit the quiz at the bottom of the page.

Example

Example
{isLoggedIn ? <Dashboard /> : <Login />}
{items.length > 0 && <List items={items} />}
Try it Yourself »

Discussion

Loading…