← React tutorial

React

Conditional Rendering

Since JSX is just JavaScript, you use normal JavaScript to decide what to render, no special "if tag" exists in JSX itself.

Example 1: a ternary for an either/or choice

function Status({ loggedIn }) {
  return <p>{loggedIn ? "Welcome back!" : "Please log in."}</p>;
}

A ternary (condition ? a : b) fits neatly inline inside JSX, which is why it's the most common choice for a simple two-way choice like this one.

Example 2: && for "render this, or render nothing"

function Notification({ hasUnread }) {
  return (
    <div>
      <p>Inbox</p>
      {hasUnread && <span>You have unread messages</span>}
    </div>
  );
}

condition && element renders the element only when the condition is true, and renders nothing at all when it's false, a clean way to express "show this, or don't," when there's no meaningful alternative content for the false case (unlike the ternary example, which had a real "else" branch).

Example 3: an if statement above the return, for bigger decisions

function Page({ user }) {
  if (!user) {
    return <p>Loading...</p>;
  }
  return <h1>Welcome, {user.name}!</h1>;
}

When the decision is more substantial than one small piece of markup, here, an entirely different component output depending on whether data has loaded yet, a plain if before the return is clearer than trying to cram the whole decision into a ternary.

Example
function Status({ loggedIn }) {
  return (
    <p>{loggedIn ? "Welcome back!" : "Please log in."}</p>
  );
}
Output
<Status loggedIn={true} /> renders "Welcome back!"; <Status loggedIn={false} /> renders "Please log in."
Ready to go further?

These free tutorials are a preview, our Frontend Development cohort covers it in depth, with a real project and a cohort alongside you. Closes Nov 30

Enroll in Frontend Development

Cookie preferences

Choose what you're comfortable with. You can change this any time from the footer.

Don't miss out

Ready to build something real?

Create a free account to enroll in a track, and get notified the moment a cohort opens.

Create free account