Conditional Rendering

Show different things depending on state, with a ternary, with &&, and with an early return. Click Log in and watch the page change.

React · beginner · 7 min · 13 steps · free

What you'll learn

Conditional.jsx

import { useState } from 'react';

function Inbox({ count }) {
  if (count === 0) {
    return <p>No new messages.</p>;
  }
  return <p>You have {count} new messages.</p>;
}

export default function App() {
  const [loggedIn, setLoggedIn] = useState(false);

  return (
    <div>
      {loggedIn ? <Inbox count={3} /> : <p>Please log in.</p>}
      <button onClick={() => setLoggedIn(!loggedIn)}>
        {loggedIn ? 'Log out' : 'Log in'}
      </button>
      {loggedIn && <small>Signed in as Ada</small>}
    </div>
  );
}

Step by step

  1. React renders <App> for the first time: it calls the App function.
  2. useState runs for the first time, so React stores the starting value for loggedIn and returns it: false.
  3. loggedIn is false, so the ternary picks <p>Please log in.</p>, and loggedIn && … adds nothing.
  4. React turns the JSX into real page elements and shows them: look at the Screen panel.
  5. You click "Log in". The arrow function in onClick runs.
  6. setLoggedIn(!loggedIn) does not change loggedIn right away: React queues the update and will render again. In this call loggedIn is still false.
  7. React renders <App> again (render 2): it calls App once more, from the top.
  8. useState returns the value React has kept for loggedIn: true. The starting value is only used on the first render.
  9. Now loggedIn is true: the ternary picks <Inbox count={3} />, the button says "Log out", and && adds the <small> line.
  10. Inbox is on the page for the first time, so React calls it with count = 3.
  11. count === 0 is false, so the early return is skipped.
  12. Inbox returns JSX: a description of what the screen should show, <p>You have 3 new messages.</p>. React has not changed the page yet.
  13. React swaps the paragraph for the inbox message, renames the button, and adds the signed-in line.

Common mistakes

Best practices

Key takeaways

Check yourself

{false && <p>Hi</p>} shows?

Answer: Nothing. false renders nothing.

{0 && <p>Hi</p>} shows?

Answer: 0. 0 is a number, and React renders numbers.

·

More in Components and JSX