Skip to the workspace
Pebellslearn by building
Rendering  ›  Lesson

Conditional Rendering

Conditional Rendering 13 minReact shows different markup under different conditions using an early return, the ternary operator, or the && operator, all ordinary JavaScript.

react / Conditional Rendering

Explore each scene at your own pace.

01 · The rule

The rule

Conditional Rendering

A book you have finished should say Finished; one you have not should say To read. A card with notes shows a little badge; one without shows nothing. There is no special React syntax for this — you use ordinary JavaScript, placed where JSX can accept it.

The rule

Two choices: ternary. Something or nothing: &&. Nothing at all: return null.

Two choices — the ternary. Inside braces, condition ? a : b picks one of two pieces of markup:

<p>{read ? 'Finished' : 'To read'}</p>

Something or nothing — &&. condition && markup shows the markup when the condition is true and nothing when it is false, because React ignores false, null and undefined:

{favourite && <span className="star">★</span>}

Nothing at all — early return. A component can stop before its main JSX. An if statement works here because it sits outside the returned markup:

function BookCard({ title, read, notes, hidden }) {
  if (hidden) return null;

  return (
    <article className="book">
      <h2>{title}</h2>
      <p>{read ? 'Finished' : 'To read'}</p>
      {notes > 0 && <span className="badge">{notes} notes</span>}
    </article>
  );
}

For anything more tangled, compute a variable before the return using plain if/else, then drop the variable into the JSX with braces:

let status;
if (read) status = <strong>Finished</strong>;
else if (pagesLeft < 20) status = <em>Almost there</em>;
else status = 'To read';

return <p>{status}</p>;

This keeps the markup readable and lets you use every tool JavaScript offers, since the decisions happen outside the JSX.

Scene 1 of 5
Hover to wake the cannons. Drag to move, or use arrow keys when focused. Press Enter to fire a shot.