Course map
Stage 1: Foundation
Stage 2: Intermediate
Stage 3: Advanced
Stage 4: Routing and Application Architecture
Stage 5: Specialization (pick ONE)

Part 04 / Stage 1

Rendering lists and conditionals

Goal: Render an array of data with .map(), choose a key that actually stays stable when the array changes, show or hide UI with &&, the ternary, and early return, and avoid the "0 renders as text" trap - all backed by a real restaurant menu with an out-of-stock state. Time: ~4 hours · Level: comfortable with modern JS and HTML, finished Parts 1–3

What you will learn

  • Turning a plain JS array into a list of elements with .map() - no new React syntax, the same array method this course's prerequisites already assume
  • Why key exists at all, and what React actually uses it for when a list changes
  • The index-as-key bug: a real, reproduced case of one item's typed-in text sticking to the wrong row after another row is removed
  • && for "render this or render nothing," the ternary for "render exactly one of these two," and early return for "bail out of this component before its main JSX"
  • The "0 renders as text" gotcha - why count && <Badge /> can put a literal 0 on screen - reproduced for real, then fixed
  • Showing a deliberate empty state instead of a blank screen when a list has nothing to show
  • Filtering a list as the user types, the same .filter() method from this course's prerequisites, now driving what .map() renders
  • This part's running example: a Rohan's Tiffin Center menu browser with search and an out-of-stock state

A note on how this part is organised: same convention as Parts 1–3 - every examples/ and solutions/ file here is wired into this repo's own harness/ and actually executed before being shown below. When you build along, type the code into your own project; this repo's copy is the verified reference, not something you need to open.

Topics in this part

Practice

Every exercise below is a React component or helper function (.jsx), each paired with a .test.jsx that actually renders or calls it with Testing Library/Vitest - the same verified-output rule as every example in this course.


Exercise 1: A list with a stable key

Scenario: Rajesh's cab app needs a ride-history screen: every past ride's pickup area and fare, newest first. What to do: Write RideHistoryList({ rides }), where each ride is { id, pickupArea, fare }. Render one <li> per ride showing "<pickupArea> - ₹<fare>". Key each <li> by ride.id, not by its position in the array.

Sample output (really rendered, React 19.3.1):

rides = [
  { id: "r1", pickupArea: "Koramangala", fare: 240 },
  { id: "r2", pickupArea: "Indiranagar", fare: 180 },
]
→ Koramangala - ₹240
  Indiranagar - ₹180

💡 Hint: rides.map((ride) => <li key={ride.id}>{${ride.pickupArea} - ₹${ride.fare}}</li>) - section 1's MenuList is this exact shape, renamed.


Exercise 2: && without the 0-leaks-through trap

Scenario: A food delivery app shows an unread-notifications badge on a bell icon - but only when there is at least one unread notification. What to do: Write NotificationBell({ unreadCount }). Always render the word "Bell". Only when unreadCount is greater than zero, also render a badge showing that count. Make sure a 0 count renders no badge at all - not a visible 0.

Sample output (both really rendered):

<NotificationBell unreadCount={0} />
→ Bell          (no badge, no stray "0" anywhere in the output)

<NotificationBell unreadCount={5} />
→ Bell
  5

💡 Hint: this is section 5's gotcha, on purpose - write unreadCount > 0 && <span>{unreadCount}</span>, not unreadCount && <span>{unreadCount}</span>, and prove the difference by actually rendering the 0 case and reading the container's text content.


Exercise 3: Early return for a special case

Scenario: An e-commerce order-status card renders very differently for a cancelled order than for a normal one - a cancelled order shows only a short apology line, nothing else about items or delivery date. What to do: Write OrderStatusCard({ order }), where order is { customerName, status, deliveryDate, itemCount }. If order.status === "cancelled", return early with just "Sorry <customerName>, this order was cancelled." and nothing else. Otherwise render customerName, itemCount, and deliveryDate.

Sample output (both really rendered):

<OrderStatusCard order={{ customerName: "Meera", status: "cancelled", deliveryDate: "12 Dec", itemCount: 3 }} />
→ Sorry Meera, this order was cancelled.
  (no item count, no delivery date anywhere in the output)

<OrderStatusCard order={{ customerName: "Asha", status: "confirmed", deliveryDate: "15 Dec", itemCount: 2 }} />
→ Asha
  2 item(s)
  Arriving 15 Dec

💡 Hint: if (order.status === "cancelled") { return <p>...</p>; } before the rest of the component's return - the same shape as this part's MenuItemRow, just with a different condition.


Exercise 4: Filter a list and show a real empty state

Scenario: A college placement portal lists companies visiting campus. Students need to search by company name, and see a clear message - not a blank screen - when a search matches nothing. What to do: Write CompanyList({ companies, query }), where each company is { id, name, role }. Render only the companies whose name includes query (case-insensitive), as "<name> - <role>". When nothing matches, render No companies match "<query>". instead of an empty list.

Sample output (really rendered, three companies in the array):

companies = [
  { id: "c1", name: "Infosys", role: "SDE" },
  { id: "c2", name: "TCS", role: "Analyst" },
  { id: "c3", name: "Flipkart", role: "SDE" },
]

query = "i"     -> Infosys - SDE
                   Flipkart - SDE

query = "wipro" -> No companies match "wipro".

💡 Hint: companies.filter((c) => c.name.toLowerCase().includes(query.toLowerCase())) feeding .map(), then a ternary on visibleCompanies.length === 0 at the list's root - this part's MenuBrowser is exactly this shape, minus the search <input> itself (take query as a plain prop here, no useState needed for this exercise).


Exercise 5: Reproduce and fix the index-as-key bug yourself

Scenario: A hostel chores app lists this week's assigned chores, each with an editable "swap request" note field. Students reported that after marking the first chore done (removing it from the list), someone else's swap request showed up attached to the wrong chore. What to do: Write two components, ChoreListBrokenKey and ChoreListFixedKey, both starting from the same three chores ({ id, task }) and both rendering an uncontrolled note <input> per chore plus a "Mark first chore done" button that removes the first chore from state. The broken version keys each row by array index; the fixed version keys by chore.id. Prove the difference the way this part's lesson did: type into the second chore's note, click the button, then check which chore's note actually holds that text afterward.

Sample output (really run, @testing-library/user-event, three chores: Sweeping, Dishes, Laundry):

BROKEN:
1. Type "ask Priya to swap" into Dishes's note.
2. Click "Mark first chore done" (removes Sweeping).
3. Dishes's note (now first in the list) is EMPTY.
   Laundry's note (now second) reads "ask Priya to swap" - wrong chore.

FIXED:
1. Type "ask Priya to swap" into Dishes's note.
2. Click "Mark first chore done" (removes Sweeping).
3. Dishes's note still reads "ask Priya to swap" - correct chore.
   Laundry's note is still empty.

💡 Hint: this is examples/02_key_prop_bug.jsx's exact shape - a different domain, same bug, same fix. key={index} versus key={chore.id} is the only line that should differ between your two components.


Exercise 6: Combine filtering, an out-of-stock state, and a live count

Scenario: Meera General Store's quick-order screen needs a product search box, a disabled "Add" button for out-of-stock products, and a count of how many products are currently visible after filtering - shown only when it is useful. What to do: Write QuickOrderList({ products, query }), where each product is { id, name, price, inStock }. Render the filtered-by-name list (case-insensitive, same as Exercise 4) with a disabled "Out of stock" button for any inStock: false product and an enabled "Add" button otherwise. Above the list, show "<n> result(s)" only when there is at least one visible result after filtering - showing nothing (not a 0 result(s) line) when the search matches nothing, since the empty-state message below already says that.

Sample output (really rendered, four products, query "a"):

products = [
  { id: "p1", name: "Atta 5kg", price: 260, inStock: true },
  { id: "p2", name: "Maggi", price: 60, inStock: true },
  { id: "p3", name: "Basmati Rice 5kg", price: 450, inStock: false },
  { id: "p4", name: "Ghee 500ml", price: 320, inStock: true },
]

query = "a" -> "3 result(s)"
              Atta 5kg - ₹260, enabled "Add"
              Maggi - ₹60, enabled "Add"
              Basmati Rice 5kg - ₹450, disabled "Out of stock"

query = "xyz" -> (no "result(s)" line at all)
                 No products match "xyz".

💡 Hint: this is this part's MenuBrowser (section 8) plus the per-row stock ternary, plus one more && guarding the count line - visibleProducts.length > 0 && <p>{${visibleProducts.length} result(s)}</p> - the same "compare, don't trust truthiness" rule from section 5 applies to this count too.

Show the solutions for Part 4 (12 files)

solutions/ex01_ride_history_list.jsx

// Exercise 1 solution: this part's MenuList (section 1), renamed for a ride
// history screen. `.map()` over the array, one `<li>` per ride, keyed by the
// ride's own stable `id` - never by position in the array.

export function RideHistoryList({ rides }) {
  return (
    <ul className="ride-history-list">
      {rides.map((ride) => (
        <li key={ride.id}>{`${ride.pickupArea} - ₹${ride.fare}`}</li>
      ))}
    </ul>
  );
}

solutions/ex01_ride_history_list.test.jsx

import { render, screen } from "@testing-library/react";
import { describe, expect, it } from "vitest";
import { RideHistoryList } from "./ex01_ride_history_list.jsx";

describe("RideHistoryList renders one row per ride, in array order", () => {
  it("shows pickup area and fare for every ride", () => {
    render(
      <RideHistoryList
        rides={[
          { id: "r1", pickupArea: "Koramangala", fare: 240 },
          { id: "r2", pickupArea: "Indiranagar", fare: 180 },
        ]}
      />,
    );

    expect(screen.getByText("Koramangala - ₹240")).toBeInTheDocument();
    expect(screen.getByText("Indiranagar - ₹180")).toBeInTheDocument();
  });
});

solutions/ex02_notification_bell.jsx

// Exercise 2 solution: section 5's "0 renders as text" gotcha, applied on
// purpose. `unreadCount > 0 && ...` is a real boolean comparison, so the
// `0` case renders nothing at all - never a literal "0" badge.

export function NotificationBell({ unreadCount }) {
  return (
    <div className="notification-bell">
      <span>Bell</span>
      {unreadCount > 0 && <span className="badge">{unreadCount}</span>}
    </div>
  );
}

solutions/ex02_notification_bell.test.jsx

import { render, screen } from "@testing-library/react";
import { describe, expect, it } from "vitest";
import { NotificationBell } from "./ex02_notification_bell.jsx";

describe("NotificationBell avoids the 0-renders-as-text trap", () => {
  it("renders no badge, and no stray '0', when unreadCount is 0", () => {
    const { container } = render(<NotificationBell unreadCount={0} />);

    expect(screen.getByText("Bell")).toBeInTheDocument();
    expect(container.querySelector(".badge")).not.toBeInTheDocument();
    expect(container.textContent).toBe("Bell");
  });

  it("renders the count badge when unreadCount is greater than 0", () => {
    render(<NotificationBell unreadCount={5} />);

    expect(screen.getByText("Bell")).toBeInTheDocument();
    expect(screen.getByText("5")).toBeInTheDocument();
  });
});

solutions/ex03_order_status_card.jsx

// Exercise 3 solution: this part's MenuItemRow (section 4) - early return
// for one special case, before the "main" JSX is ever reached.

export function OrderStatusCard({ order }) {
  if (order.status === "cancelled") {
    return <p>{`Sorry ${order.customerName}, this order was cancelled.`}</p>;
  }

  return (
    <div>
      <p>{order.customerName}</p>
      <p>{`${order.itemCount} item(s)`}</p>
      <p>{`Arriving ${order.deliveryDate}`}</p>
    </div>
  );
}

solutions/ex03_order_status_card.test.jsx

import { render, screen } from "@testing-library/react";
import { describe, expect, it } from "vitest";
import { OrderStatusCard } from "./ex03_order_status_card.jsx";

describe("OrderStatusCard bails out early for a cancelled order", () => {
  it("renders only the apology line, nothing about items or delivery date", () => {
    render(
      <OrderStatusCard
        order={{ customerName: "Meera", status: "cancelled", deliveryDate: "12 Dec", itemCount: 3 }}
      />,
    );

    expect(screen.getByText("Sorry Meera, this order was cancelled.")).toBeInTheDocument();
    expect(screen.queryByText(/item\(s\)/)).not.toBeInTheDocument();
    expect(screen.queryByText(/Arriving/)).not.toBeInTheDocument();
  });

  it("renders the full details for a normal order", () => {
    render(
      <OrderStatusCard
        order={{ customerName: "Asha", status: "confirmed", deliveryDate: "15 Dec", itemCount: 2 }}
      />,
    );

    expect(screen.getByText("Asha")).toBeInTheDocument();
    expect(screen.getByText("2 item(s)")).toBeInTheDocument();
    expect(screen.getByText("Arriving 15 Dec")).toBeInTheDocument();
  });
});

solutions/ex04_company_list.jsx

// Exercise 4 solution: `.filter()` feeding `.map()`, plus a ternary at the
// list's root for the empty state (sections 6-7) - this part's MenuBrowser
// shape, minus the search <input> itself (query arrives as a plain prop
// here, no useState needed for this exercise).

export function CompanyList({ companies, query }) {
  const visibleCompanies = companies.filter((company) =>
    company.name.toLowerCase().includes(query.toLowerCase()),
  );

  if (visibleCompanies.length === 0) {
    return <p className="empty-state">{`No companies match "${query}".`}</p>;
  }

  return (
    <ul>
      {visibleCompanies.map((company) => (
        <li key={company.id}>{`${company.name} - ${company.role}`}</li>
      ))}
    </ul>
  );
}

solutions/ex04_company_list.test.jsx

import { render, screen } from "@testing-library/react";
import { describe, expect, it } from "vitest";
import { CompanyList } from "./ex04_company_list.jsx";

const companies = [
  { id: "c1", name: "Infosys", role: "SDE" },
  { id: "c2", name: "TCS", role: "Analyst" },
  { id: "c3", name: "Flipkart", role: "SDE" },
];

describe("CompanyList filters case-insensitively", () => {
  it("shows only the companies whose name matches the query", () => {
    render(<CompanyList companies={companies} query="i" />);

    expect(screen.getByText("Infosys - SDE")).toBeInTheDocument();
    expect(screen.getByText("Flipkart - SDE")).toBeInTheDocument();
    expect(screen.queryByText("TCS - Analyst")).not.toBeInTheDocument();
  });

  it("shows a real empty state, not a blank list, when nothing matches", () => {
    render(<CompanyList companies={companies} query="wipro" />);

    expect(screen.getByText('No companies match "wipro".')).toBeInTheDocument();
    expect(screen.queryByRole("list")).not.toBeInTheDocument();
  });
});

solutions/ex05_chore_list_key_bug.jsx

// Exercise 5 solution: this part's OrderNotesBrokenKey/OrderNotesFixedKey
// (section 3) - the exact same bug and fix, renamed for a hostel chores app.
// Uncontrolled note <input>s on purpose, so their typed text lives in the
// real DOM node, not in React state the next render would recompute anyway.

import { useState } from "react";

const initialChores = [
  { id: "sweeping", task: "Sweeping" },
  { id: "dishes", task: "Dishes" },
  { id: "laundry", task: "Laundry" },
];

function ChoreRow({ chore }) {
  return (
    <li>
      <span>{chore.task}</span>{" "}
      <input aria-label={`swap note for ${chore.id}`} placeholder="swap request" />
    </li>
  );
}

// BROKEN: key is the array index. Removing the first chore shifts every
// later chore's index down by one, so React reuses the wrong <li>/<input>
// DOM nodes instead of removing one and leaving the other two untouched.
export function ChoreListBrokenKey() {
  const [chores, setChores] = useState(initialChores);
  return (
    <div>
      <button onClick={() => setChores((current) => current.slice(1))}>Mark first chore done</button>
      <ul>
        {chores.map((chore, index) => (
          <ChoreRow key={index} chore={chore} />
        ))}
      </ul>
    </div>
  );
}

// FIXED: key is the chore's own, stable id - it never changes when the
// array around it changes, so React can tell exactly which chore left.
export function ChoreListFixedKey() {
  const [chores, setChores] = useState(initialChores);
  return (
    <div>
      <button onClick={() => setChores((current) => current.slice(1))}>Mark first chore done</button>
      <ul>
        {chores.map((chore) => (
          <ChoreRow key={chore.id} chore={chore} />
        ))}
      </ul>
    </div>
  );
}

solutions/ex05_chore_list_key_bug.test.jsx

import { render, screen } from "@testing-library/react";
import userEvent from "@testing-library/user-event";
import { describe, expect, it } from "vitest";
import { ChoreListBrokenKey, ChoreListFixedKey } from "./ex05_chore_list_key_bug.jsx";

describe("ChoreListBrokenKey: index-as-key reuses the wrong DOM node", () => {
  it("sticks the typed note to the wrong chore after the first one is removed", async () => {
    const user = userEvent.setup();
    render(<ChoreListBrokenKey />);

    await user.type(screen.getByLabelText("swap note for dishes"), "ask Priya to swap");
    await user.click(screen.getByRole("button", { name: "Mark first chore done" }));

    // Dishes is now first (Sweeping removed) - its note is empty, because
    // the DOM node at this position used to be Sweeping's, whose note was
    // always blank.
    expect(screen.getByLabelText("swap note for dishes")).toHaveValue("");
    // Laundry is now second - it inherited the DOM node that held the typed
    // text, because its position's key ("1") matched on both renders.
    expect(screen.getByLabelText("swap note for laundry")).toHaveValue("ask Priya to swap");
  });
});

describe("ChoreListFixedKey: a stable id key keeps notes with the right chore", () => {
  it("keeps the typed note on Dishes after the first chore is removed", async () => {
    const user = userEvent.setup();
    render(<ChoreListFixedKey />);

    await user.type(screen.getByLabelText("swap note for dishes"), "ask Priya to swap");
    await user.click(screen.getByRole("button", { name: "Mark first chore done" }));

    expect(screen.getByLabelText("swap note for dishes")).toHaveValue("ask Priya to swap");
    expect(screen.getByLabelText("swap note for laundry")).toHaveValue("");
  });
});

solutions/ex06_quick_order_list.jsx

// Exercise 6 solution: this part's MenuBrowser (section 8) plus the per-row
// stock ternary, plus one more `&&` guarding the result count - the same
// "compare, don't trust truthiness" rule from section 5 applies to this
// count too, so an empty result never shows a stray "0 result(s))" line.

export function QuickOrderList({ products, query }) {
  const visibleProducts = products.filter((product) =>
    product.name.toLowerCase().includes(query.toLowerCase()),
  );

  return (
    <div className="quick-order-list">
      {visibleProducts.length > 0 && <p>{`${visibleProducts.length} result(s)`}</p>}
      {visibleProducts.length === 0 ? (
        <p className="empty-state">{`No products match "${query}".`}</p>
      ) : (
        <ul>
          {visibleProducts.map((product) => (
            <li key={product.id}>
              <span>{product.name}</span> <span>{`₹${product.price}`}</span>{" "}
              <button disabled={!product.inStock}>{product.inStock ? "Add" : "Out of stock"}</button>
            </li>
          ))}
        </ul>
      )}
    </div>
  );
}

solutions/ex06_quick_order_list.test.jsx

import { render, screen } from "@testing-library/react";
import { describe, expect, it } from "vitest";
import { QuickOrderList } from "./ex06_quick_order_list.jsx";

const products = [
  { id: "p1", name: "Atta 5kg", price: 260, inStock: true },
  { id: "p2", name: "Maggi", price: 60, inStock: true },
  { id: "p3", name: "Basmati Rice 5kg", price: 450, inStock: false },
  { id: "p4", name: "Ghee 500ml", price: 320, inStock: true },
];

describe("QuickOrderList combines filtering, stock state, and a live count", () => {
  it("shows a result count and the right button state per product", () => {
    render(<QuickOrderList products={products} query="a" />);

    expect(screen.getByText("3 result(s)")).toBeInTheDocument();
    expect(screen.getByText("Atta 5kg")).toBeInTheDocument();
    expect(screen.getAllByRole("button", { name: "Add" })).toHaveLength(2);
    expect(screen.getByRole("button", { name: "Out of stock" })).toBeDisabled();
  });

  it("hides the result count entirely and shows the empty state when nothing matches", () => {
    render(<QuickOrderList products={products} query="xyz" />);

    expect(screen.queryByText(/result\(s\)/)).not.toBeInTheDocument();
    expect(screen.getByText('No products match "xyz".')).toBeInTheDocument();
  });
});

Common mistakes

Mistake Why it is wrong Fix
items.map(item => <li>...) with no key at all React warns in the console on every such render; the warning is a real signal, not noise to silence Add key={item.id} (or any other value stable per item)
key={index} on a list that can be reordered, filtered, or have items added/removed from anywhere but the end React matches old-key-to-new-key by position, not by identity - unrelated DOM state (typed text, scroll position, open/closed toggles) can end up attached to the wrong item, with no error at all (section 3) Key by the item's own stable id - a database id, a slug, anything that travels with that specific item, never its position
key={Math.random()} "to make the warning go away" A brand-new key every render means React treats every item as brand new every render too - it remounts the whole list each time, which is slower and throws away exactly the DOM state a stable key is supposed to protect Use a value that is the same across renders for the same logical item
count && <Badge /> where count can be 0 && returns 0 itself when its left side is falsy, and React renders that 0 as visible text (section 5) Compare instead of trusting truthiness: count > 0 && <Badge />
A blank <ul></ul> when a filtered list has nothing left Looks identical to a loading state or a broken screen - gives the user no information Branch explicitly on items.length === 0 and show a real empty-state message
Nesting three or more ? : inside one JSX expression Technically legal, unreadable in practice - this course never does it Pull the logic above the return into a named variable or helper function, or switch to an early return
Checking item.available ? <Row /> : null when a plain && says the same thing more directly Not wrong, just noisier than it needs to be once there is no real "else" content Use && when the false branch is "render nothing," reserve the ternary for two real outcomes

Quick recap

  • .map() turns a data array into an array of elements; React renders that array the same way it renders one element.
  • key exists so React can tell "same logical item" from "different item" across a re-render - it is never a styling hook and never reaches the DOM.
  • An array index looks like a unique key but is not stable - removing, inserting, or reordering shifts which item each index belongs to, and a reproduced bug (section 3) shows exactly what breaks when per-item DOM state gets reused for the wrong item.
  • && renders-or-nothing, the ternary renders-exactly-one-of-two, early return bails out of a whole component for one case - pick based on how many real outcomes there are.
  • count && <X /> renders a literal 0 when count is 0, because && returns its falsy left side as-is; compare (count > 0) instead of trusting truthiness.
  • An empty list deserves a deliberate empty-state branch, not a blank <ul>.
  • .filter() feeding .map() is the whole mechanism behind search-as-you-type - no separate "filtered list" state needed, because the filter re-runs on every render.

Checklist

  • I rendered a list from a plain array with .map() and gave every item a key built from its own data, not its position.
  • I captured React's real "missing key" console warning by rendering a list with no key, instead of only reading about it.
  • I reproduced the index-as-key bug myself - typed into one row, removed an earlier row, and watched the typed value stick to the wrong row - then fixed it with a stable id key.
  • I can say, without looking it up, when to reach for &&, when for a ternary, and when for an early return.
  • I reproduced the "0 renders as text" bug with a real falsy count, saw the literal 0 on screen, and fixed it by comparing instead of trusting truthiness.
  • I built a list that shows a real empty-state message instead of a blank list when nothing matches.
  • I combined .filter() and .map() to filter a list as the user types into a search box.

Search the guide