Conditional Rendering in React: 5 Patterns with Runnable Examples

Learn when to use early returns, ternaries, logical AND, null, and switch through a course dashboard you can run and test with five UI states.

KnowledgeGate Team

Exam prep & CS education

Updated 2 Dec 20265 min read
Conditional Rendering in React: 5 Patterns with Runnable Examples

JSX can show a fixed heading easily. A real interface must choose among loading, error, signed-out, in-progress, and completed states. Conditional rendering uses ordinary JavaScript to select the element tree, text value, or null for the current state.

Conditional rendering in React: the decision before the JSX

Conditional rendering means choosing which React element tree, text value, or null a component returns for its current props and state. Start with const isLoggedIn = false. The expression isLoggedIn ? <Dashboard /> : <Login /> chooses Login. Change the value to true, and the same expression chooses Dashboard.

Keep three decisions separate. Replace a whole screen with an early return. Choose between two inline elements with a ternary. Add one optional element with logical &&. For three or more named states, use a switch or a helper component. This distinction is useful throughout a web-development learning path. It is different from hiding an element with CSS, because that element still exists in the rendered tree.

Choose among five patterns without nesting a puzzle

Use the form that makes every possible UI state obvious at a glance.

Pattern

Best use

if plus early return

Mutually exclusive page states

condition ? A : B

Exactly two visible outcomes

condition && A

One optional addition

return null

A component should contribute no UI

switch or helper

Three or more named states

These tools produce values React renders. If score = 72, then score >= 40 ? "Pass" : "Retry" returns "Pass". If isNew = true, isNew && <span>New</span> renders the badge. If isNew = false, it adds no badge. Avoid nested ternaries for a multi-state dashboard because their order is hard to check.

Worked example: render five exact CourseDashboard states

Run this component with Asha's default mid-course data.

jsx
function CourseDashboard({ isLoading, error, learner }) {
  if (isLoading) return <p>Loading your dashboard...</p>;
  if (error) return <p role="alert">{error}</p>;
  if (!learner) return <button>Log in to continue</button>;

  const remaining = learner.totalLessons - learner.completedLessons;

  return (
    <section>
      <h2>Welcome, {learner.name}</h2>
      <p>{learner.completedLessons} of {learner.totalLessons} lessons completed</p>
      {remaining > 0
        ? <button>Continue: {learner.nextLesson}</button>
        : <strong>Course complete</strong>}
      {learner.hasCertificate && <button>Download certificate</button>}
    </section>
  );
}

const asha = {
  name: "Asha",
  completedLessons: 3,
  totalLessons: 5,
  nextLesson: "React Lists",
  hasCertificate: false
};

export default function App() {
  return <CourseDashboard isLoading={false} error={null} learner={asha} />;
}

For Asha, remaining = 5 - 3 = 2. The output is Welcome, Asha, 3 of 5 lessons completed, and Continue: React Lists, with no certificate button. The first three early returns keep loading, error, and guest branches out of the main JSX.

Check four replacements. isLoading={true} shows only Loading your dashboard.... With loading false, error="Could not load progress" shows only that alert. With no error, learner={null} shows only Log in to continue. Kabir with completedLessons: 5, totalLessons: 5, nextLesson: null, and hasCertificate: true has remaining = 5 - 5 = 0. He sees Welcome, Kabir, 5 of 5 lessons completed, Course complete, and Download certificate.

Decision tree for loading, error, learner, and course completion states in CourseDashboard.

Ternary and logical AND inside one rendered branch

Asha has remaining = 2. A ternary suits the action because the interface must show either Continue: React Lists or Course complete, never both. Keep its branches aligned, and extract them if either grows beyond one small element.

Logical && is an optional addition, not an either-or choice. Asha's false value adds no certificate button. Kabir's true value adds Download certificate after Course complete.

Element choice still matters: use a real button for an action and role="alert" for this error message, not a clickable div.

Matrix showing ternary, logical AND, and explicit Boolean checks for dashboard rendering.

Return null or use switch when the branch shape changes

Use null when a component should contribute no UI for a render:

jsx
function PromoBanner({ eligible }) {
  if (!eligible) return null;
  return <aside>New course available</aside>;
}

With eligible = false, PromoBanner contributes no UI. With eligible = true, the banner appears. It is unmounted only if its parent stops rendering it.

For named states, a switch keeps every outcome explicit:

jsx
function SaveMessage({ status }) {
  switch (status) {
    case "saving": return <p>Saving profile...</p>;
    case "saved": return <p>Profile saved</p>;
    case "error": return <p role="alert">Save failed. Try again.</p>;
    default: return null;
  }
}

The inputs "saving", "saved", and "error" produce those messages. "idle" or an unknown value produces no UI. One status is safer than contradictory booleans such as isSaving = true and hasError = true.

Common errors: visible zeroes, conditional hooks and unreadable branches

A number needs an explicit Boolean check. With unreadCount = 0, this expression evaluates to 0, which React can display:

jsx
{unreadCount && <p>{unreadCount} unread</p>}

Use {unreadCount > 0 && <p>{unreadCount} unread</p>} instead. With unreadCount = 0, it adds nothing. With unreadCount = 4, it displays 4 unread.

Do not call a Hook conditionally:

jsx
if (learner) {
  const [tab, setTab] = useState("overview");
}

Call const [tab, setTab] = useState("overview") at the component's top level, then make only the returned JSX conditional. This preserves the same Hook call order on every render. The React Hooks guide owns state, effects, memoisation, and custom hooks; this tutorial owns the rendering branches that consume their values.

Replace loading ? A : error ? B : learner ? C : D with named early returns. Replace impossible Boolean combinations with one status such as "loading" | "error" | "guest" | "ready". Also remember that an if statement cannot sit directly inside JSX braces, because JSX expects an expression there.

Exercises and interview-style output checks

  1. Build NotificationBadge({ unreadCount }). Input 0 must render nothing, while input 4 must render 4 unread. Use the unreadCount > 0 guard, so no visible 0 can leak into the page.

  2. Build TrafficLight({ status }) with a switch: "red" gives Stop, "amber" gives Wait, "green" gives Go, and any other value gives Unknown signal. Exactly one label should appear for each input.

  3. Extend CourseDashboard with role = "student" | "instructor". A student sees Continue: React Lists, an instructor sees Edit course, and any other role sees View course. Keep Asha at 3 of 5 lessons so only the role decision changes, and render exactly one course action.

Predict two more outputs. If loading is true and an error string also exists, Loading your dashboard... wins because its early return comes first. If a component's condition fails and it explicitly returns null, that component contributes no UI for the render.

The short version and the next study step

Use an early return for whole states, a ternary for A-or-B, && for an optional element after converting numeric conditions to Booleans, null for no UI, and a switch or helper for named multi-state logic. In the dashboard, precedence is loading, error, guest, then ready. For guided React and Redux practice, see the React and Redux Course. To place React inside a full-stack project path, explore the MERN Stack Course.