Conditional Rendering

View saved

If / else with early return

Return different JSX from branches when the layouts differ a lot.

function Status({ ready }) {
  if (!ready) {
    return <p>Loading…</p>;
  }
  return <p>Ready</p>;
}

Ternary in JSX

Use a ternary for small either/or choices inline.

{isLoggedIn ? <Dashboard /> : <LoginPrompt />}

Logical AND for optional UI

Render something only when a condition is true.

{error && <p className="error">{error}</p>}

Prefer clear conditions

  • Avoid nested ternaries that are hard to read
  • Extract a small component when branches grow large
  • Remember that 0 is falsy—be careful with count && ...

Comments

One comment per signed-in account. Comments are saved with this page’s URL.