DevPath · Learn to code ESPTEN

Lists and conditional rendering

Conditional rendering

Showing things based on a condition

Often you want to paint something only if a condition is met: an error message, a spinner while loading, a greeting if the user has logged in. Since JSX lives inside JavaScript, you use the same tools as always.

The && operator

The most common pattern for "show this only if the condition is true":

function Inbox({ unread }) {
  return (
    <div>
      <h1>Inbox</h1>
      {unread > 0 && <p>You have {unread} unread messages</p>}
    </div>
  );
}

If the condition is true, the right side is evaluated and painted. If it is false, React renders nothing (it ignores the values false, null, and undefined).

Beware of 0: {list.length && <List/>} would paint a 0 on screen when the list is empty, because 0 is not true but it is not ignored either. Use a clear boolean condition: {list.length > 0 && <List/>}.

The ternary operator ? :

When you want to choose between two alternatives ("this or that"), use the ternary condition ? ifTrue : ifFalse:

function Access({ loggedIn }) {
  return (
    <p>{loggedIn ? "Welcome back" : "Sign in"}</p>
  );
}

You can also return complete elements in each branch:

{loggedIn ? <Profile /> : <Login />}

Returning null to render nothing

A component that returns null paints absolutely nothing. It is useful for hiding an entire component based on a condition:

function Notice({ visible, text }) {
  if (!visible) return null;
  return <div className="notice">{text}</div>;
}

Returning null is perfectly valid and is not an error: it simply tells React that there is nothing to show there.

Put this into practice

DevPath is a hands-on course: you read the theory here; in the app you put it into practice with exercises that really run, offline.

Start free in the app →
← Render lists with .map() and keyFragments: group without an extra div →