ReactEasy

What is conditional rendering?

Conditional rendering means showing different JSX depending on conditions, using normal JavaScript: if statements with early returns, the ternary operator (a ? b : c), logical AND (cond && <X />), or a lookup object. Returning null renders nothing.

Techniques

  • Early return: if (loading) return <Spinner />; keeps the main JSX clean.
  • Ternary: {isAdmin ? <AdminPanel /> : <UserPanel />} for either/or.
  • Logical AND: {error && <Alert>{error}</Alert>} for "show or nothing".
  • Variables: compute let content with if/else, then render {content}.
  • Object maps: const views = { list: <List />, grid: <Grid /> }; return views[mode];.
  • null to render nothing.

The && trap

{count && <Badge />} renders 0 when count is 0, because React renders numbers. Use {count > 0 && <Badge />} or a ternary. false, null, undefined and true render nothing.

State implications

  • Switching between different component types at the same position remounts them and resets state.
  • Rendering the same type in both branches keeps state; add a key if you want a reset.
  • To hide something while preserving its state and DOM, React 19.2's <Activity mode="hidden"> hides it and pauses its effects instead of unmounting.

Readability

Avoid nested ternaries; extract components or use early returns.

Code example

tsx
1import { Activity, useState } from "react";
2
3type Status = "loading" | "error" | "empty" | "ready";
4
5export function Inbox({ status, count, error }: { status: Status; count: number; error?: string }) {
6 const [showDraft, setShowDraft] = useState(false);
7
8 if (status === "loading") return <p>Loading…</p>; // early return
9 if (status === "error") return <p role="alert">{error}</p>;
10
11 return (
12 <section>
13 <h2>Inbox {count > 0 && <span className="badge">{count}</span>}</h2>
14 {/* {count && <span/>} would render "0" */}
15 {status === "empty" ? <p>No messages</p> : <p>You have {count} messages</p>}
16
17 <button onClick={() => setShowDraft((s) => !s)}>Toggle draft</button>
18 {/* Keeps the textarea's text while hidden (React 19.2) */}
19 <Activity mode={showDraft ? "visible" : "hidden"}>
20 <textarea placeholder="Draft a reply" />
21 </Activity>
22 </section>
23 );
24}

Practice this question

Open it in the study app to track progress, take notes, listen to the answer and work through the rest of the React set.

Open in study app