Conditional rendering

Topic 4 of 5 in JSX & components6 min readIntermediateFree course

Overview

Real interfaces change with the data: show a spinner while loading, an error if something failed, a login link for guests, a badge for new courses. Because JSX is JavaScript, you don’t need special template syntax for this — you use the conditionals you already know.

if statements and early returns

if can’t go inside JSX braces (it’s a statement), but it works perfectly in the component body:

JSX
function CourseList({ courses, isLoading, error }) {
  if (isLoading) {
    return <Spinner />;
  }

  if (error) {
    return <p className="error">Couldn’t load courses: {error.message}</p>;
  }

  if (courses.length === 0) {
    return <EmptyState>No courses match your search.</EmptyState>;
  }

  return (
    <ul>
      {courses.map((c) => <CourseRow key={c.id} course={c} />)}
    </ul>
  );
}

Early returns handle the special cases first, leaving the “happy path” clean at the bottom. This is the most readable pattern when whole sections of UI differ.

Rendering nothing

A component can return null to render nothing at all:

JSX
function SaleBanner({ sale }) {
  if (!sale) return null;
  return <div className="banner">{sale.percent}% off everything!</div>;
}

Often, though, it’s clearer for the parent to decide whether to render a component at all, rather than the component hiding itself.

The ternary operator

For “this or that” inside JSX, use the conditional (ternary) operator:

JSX
<button>
  {isEnrolled ? 'Continue learning' : 'Enrol now'}
</button>

<p className={isOverdue ? 'due overdue' : 'due'}>Due {dueDate}</p>

{isEditing ? (
  <CourseForm course={course} onSave={handleSave} />
) : (
  <CourseDetails course={course} />
)}

Ternaries work anywhere an expression is allowed: text, attribute values, whole elements. Wrap multi-line JSX branches in parentheses for readability.

Logical && for “something or nothing”

When there’s no “else”, use &&:

JSX
<h2>
  {course.title}
  {course.isNew && <span className="badge">New</span>}
</h2>

In JavaScript, a && b returns a if it’s falsy, otherwise b. React renders nothing for false, so this shows the badge only when isNew is true.

The 0 trap

React renders nothing for false, null and undefined — but it does render the number 0:

JSX
{cart.items.length && <CartSummary items={cart.items} />}
// When the cart is empty this renders a stray "0" on the page!

cart.items.length is 0, which is falsy, so && returns 0 — and React displays it. Always make the left side a real boolean:

JSX
{cart.items.length > 0 && <CartSummary items={cart.items} />}
{Boolean(unreadCount) && <Badge count={unreadCount} />}
{unreadCount ? <Badge count={unreadCount} /> : null}

Conditionally assigning JSX to a variable

When the logic is too long for a ternary, assign JSX to a variable with let and if:

JSX
function LessonIcon({ lesson }) {
  let icon = <PlayIcon />;
  if (lesson.completed) {
    icon = <CheckIcon />;
  } else if (lesson.locked) {
    icon = <LockIcon />;
  }

  return (
    <span className="lesson-icon" aria-label={lesson.completed ? 'Completed' : undefined}>
      {icon}
    </span>
  );
}

This is the most flexible approach: plain JavaScript, no nested ternaries.

Lookup objects for many cases

When a value can be one of several options, an object lookup beats a chain of ternaries:

JSX
const statusLabels = {
  draft: { text: 'Draft', className: 'badge-muted' },
  published: { text: 'Live', className: 'badge-success' },
  archived: { text: 'Archived', className: 'badge-warn' },
};

function StatusBadge({ status }) {
  const { text, className } = statusLabels[status] ?? statusLabels.draft;
  return <span className={`badge ${className}`}>{text}</span>;
}

The same idea works with components as values: const views = { grid: GridView, list: ListView }; const View = views[mode]; return <View items={items} />; — note the variable must be capitalised for JSX to treat it as a component.

Name your conditions

Complex conditions inline make JSX hard to read:

JSX
// ✗ Hard to scan
{user && !user.isBanned && (course.isFree || user.subscription?.active) && <PlayButton />}

// ✓ A named variable explains the intent
const canWatch = user && !user.isBanned && (course.isFree || user.subscription?.active);
{canWatch && <PlayButton />}

Hiding vs not rendering

Conditional rendering removes the element from the DOM — and, for components, throws away their state. Sometimes you want to keep something mounted but invisible (a tab whose scroll position should survive). Options:

  • the HTML hidden attribute or a CSS class — the DOM and state stay; the element isn’t shown,
  • React’s <Activity mode="hidden">, which preserves state while hidden and pauses effects — covered in Code splitting and Activity.

Which to use? Early returns for whole-component branches, ternaries for two-way choices inside JSX, && with a real boolean for show/hide, and lookup objects for many variants.

Exercise

Course status badge

Write EnrollmentStatus({ course, user }). If there’s no user, render a “Log in to enrol” link. If course.status is 'closed', render nothing. Otherwise render a button whose text is “Continue learning” when user.enrolledIds includes course.id, and “Enrol now” when it doesn’t; when course.seatsLeft is between 1 and 5, also show “Only N seats left!”. Be careful with seatsLeft of 0.

JavaScript
export function EnrollmentStatus({ course, user }) {
  // your code here
}

Summary

  • Use plain if statements (with early returns) for larger branches of UI.
  • Use the ternary cond ? a : b inside JSX to choose between two pieces of UI.
  • Use cond && <X /> to render something or nothing — but never with a number on the left, because 0 renders.
  • Return null from a component to render nothing.
  • Use an object lookup for many cases, and extract complex conditions into well-named variables.