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

Part 02 / Stage 1

Components, props and composition

Goal: Write function components that take props the same way any JavaScript function takes arguments, give those props sensible defaults, compose components out of other components (through children and through named JSX "slot" props), and know when and how to split a growing UI into smaller pieces. Time: ~4 hours · Level: comfortable with modern JS and HTML, finished Part 1

What you will learn

  • That a prop is read exactly like any other function argument - destructuring, default values, nothing React-specific about the syntax
  • How to give a prop a default value for callers who skip it, and which props should stay required by convention instead
  • children as the simplest form of composition: whatever sits between a component's tags
  • "Slots": passing JSX through a prop that is not children, so a component can expose more than one fillable region
  • Why props are read-only, and what actually goes wrong - with no error and no warning - when a component mutates one anyway
  • A concrete way to decide when a growing component should be split into smaller ones, and proof that splitting it changes nothing about what gets rendered
  • This part's running example: one ProductCard, reused three different ways from the same component

A note on how this part is organised: same convention as Part 1 - 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 component with a default prop

Scenario: Rajesh's cinema booking app needs a reusable ticket card. Most seats are regular; only some bookings are premium. What to do: Write MovieTicketCard({ movieName, hall, seat, isPremium = false }). Render the movie name and "Hall <hall>, Seat <seat>". Show a "Premium" badge only when isPremium is true. movieName, hall and seat are required by convention (no default); isPremium has a default so most callers can skip it.

Sample output (both really rendered, React 19.3.1):

<MovieTicketCard movieName="Jawan" hall="3" seat="F12" />
→ Jawan
  Hall 3, Seat F12
  (no Premium badge)

<MovieTicketCard movieName="Pathaan" hall="1" seat="A1" isPremium />
→ Pathaan
  Hall 1, Seat A1
  Premium

💡 Hint: {isPremium && <span className="premium-badge">Premium</span>} - the same && pattern this part's lesson used for PageSection's optional slots.


Exercise 2: children works the same for text or JSX

Scenario: A food delivery app needs a reusable alert banner for order status messages - sometimes plain text, sometimes text with an emphasized order number inside it. What to do: Write Alert({ type, children }). Render a label built from type ("Error", "Warning", or "Info" - anything else should fall back to "Info"), followed by whatever children is.

Sample output (both really rendered):

<Alert type="error">Payment failed, please retry.</Alert>
→ Error: Payment failed, please retry.

<Alert type="info">Your order <strong>#1234</strong> has been packed.</Alert>
→ Info: Your order #1234 has been packed.

💡 Hint: children does not care whether it is a plain string or a mix of text and JSX - render {children} exactly the way this part's PageSection rendered its children prop, and it works for both cases with no extra code.


Exercise 3: Slots beyond children

Scenario: A customer-support chat UI needs a message bubble with three independent pieces: who sent it, what they said, and when. What to do: Write ChatMessage({ avatar, children, timestamp }), where avatar and timestamp are JSX slot props (not children) and the message text itself is passed as children.

Sample output (really rendered):

<ChatMessage avatar={<span aria-label="Ravi Shetty">RS</span>} timestamp={<time>10:42 AM</time>}>
  Your package has left the warehouse.
</ChatMessage>
→ RS
  Your package has left the warehouse.
  10:42 AM

💡 Hint: this is exactly this part's PageSection shape (header/children/footer), just renamed for a chat bubble (avatar/children/timestamp). The slot names change; the pattern does not.


Exercise 4: Find and fix a props-mutation bug

Scenario: A restaurant ordering screen renders a "cheapest picks" promo banner above the full menu, both from the same menuItems array passed down as a prop. A teammate wrote this helper for the banner:

function sortCheapestFirst(items) {
  return items.sort((a, b) => a.price - b.price);
}

After this shipped, testers reported that the full menu below the banner started showing dishes in a strange order - cheapest first - even though nobody touched the full menu's own code. What to do: Explain why this happens (in a code comment is fine), then write a fixed sortCheapestFirst that returns a cheapest-first list without ever touching the order of the array the caller passed in.

Sample output (really run - menuItems kept as a reference after calling the fixed function):

banner (cheapest first): Jeera Rice, Dal Makhani, Paneer Butter Masala
menuItems (unchanged):   Paneer Butter Masala, Dal Makhani, Jeera Rice

💡 Hint: Array.prototype.sort mutates the array it is called on and returns that same reference - this part's lesson (section 5) proved this exact thing with a products list. Copy first: [...items].sort(...).


Exercise 5: Break a monolith into named pieces

Scenario: This part's lesson split a Meera General Store receipt into OrderHeader/OrderItemsList/OrderTotal. Prove the same move works for a different domain: a cab ride receipt. What to do: Given a single, monolithic RideReceiptMonolith({ riderName, fare, distanceKm, driverName }) that renders a rider name + driver name header, a distance line, and a fare footer all in one JSX block, split it into RideHeader, RideDistance, RideFooter, composed by a new RideReceipt. Prove with renderToStaticMarkup that both versions produce identical HTML.

Sample output (really run, React 19.3.1 + react-dom/server):

composed === monolith: true

💡 Hint: same four signals as the lesson's section 6 - each piece here has a name ("header," "distance," "footer") and only needs some of the parent's props, not all of them.


Exercise 6: Drive the lesson's ProductCard from data

Scenario: This part's lesson rendered ProductCard three times by hand, with three separate JSX tags, to prove it handles a plain product, a discounted product, and an out-of-stock product. A real shop page would never hand-write a tag per product - it would map over an array. What to do: Write ProductGrid({ products }) that reuses the lesson's own ProductCard component (import it - do not rewrite it) and renders one ProductCard per entry in products, spreading each product object's fields as that card's props.

Sample output (really rendered, three products in one array):

products = [
  { name: "Atta 5kg", price: 260, imageAlt: "A 5kg bag of atta" },
  { name: "Toor Dal 1kg", price: 140, imageAlt: "A 1kg packet of toor dal", discountPercent: 20 },
  { name: "Ghee 500ml", price: 320, imageAlt: "A 500ml jar of ghee", inStock: false },
]
→ Atta 5kg: ₹260, enabled "Add to cart"
  Toor Dal 1kg: ₹140 / ₹112, "20% off", enabled "Add to cart"
  Ghee 500ml: ₹320, disabled "Out of stock"

💡 Hint: products.map((product) => <ProductCard key={product.name} {...product} />) - the spread operator turns each object's own fields into that card's props, the same object-spread syntax from the root README's JavaScript prerequisites. Part 4 covers list rendering and keys properly; a key here is enough to stop React's console from warning about a missing one.

Show the solutions for Part 2 (12 files)

solutions/ex01_movie_ticket_card.jsx

// Exercise 1 solution: a component built from scratch, the same shape as
// the lesson's ProductCard - props destructured in the parameter list,
// with a default for the one prop callers will often skip.

export function MovieTicketCard({ movieName, hall, seat, isPremium = false }) {
  return (
    <article className="movie-ticket-card">
      <h3>{movieName}</h3>
      <p>{`Hall ${hall}, Seat ${seat}`}</p>
      {isPremium && <span className="premium-badge">Premium</span>}
    </article>
  );
}

solutions/ex01_movie_ticket_card.test.jsx

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

describe("MovieTicketCard", () => {
  it("renders without a Premium badge when isPremium is left at its default", () => {
    render(<MovieTicketCard movieName="Jawan" hall="3" seat="F12" />);

    expect(screen.getByText("Jawan")).toBeInTheDocument();
    expect(screen.getByText("Hall 3, Seat F12")).toBeInTheDocument();
    expect(screen.queryByText("Premium")).not.toBeInTheDocument();
  });

  it("renders the Premium badge when isPremium is passed explicitly", () => {
    render(<MovieTicketCard movieName="Pathaan" hall="1" seat="A1" isPremium />);

    expect(screen.getByText("Pathaan")).toBeInTheDocument();
    expect(screen.getByText("Hall 1, Seat A1")).toBeInTheDocument();
    expect(screen.getByText("Premium")).toBeInTheDocument();
  });
});

solutions/ex02_alert_banner.jsx

// Exercise 2 solution: `children` accepts plain text or JSX equally - a
// component that reads `children` never needs to know which one it got.

export function Alert({ type, children }) {
  const label = type === "error" ? "Error" : type === "warning" ? "Warning" : "Info";

  return (
    <div className={`alert alert-${type}`}>
      <strong>{`${label}: `}</strong>
      {children}
    </div>
  );
}

solutions/ex02_alert_banner.test.jsx

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

describe("Alert", () => {
  it("prefixes a plain text child with a label built from the type prop", () => {
    render(<Alert type="error">Payment failed, please retry.</Alert>);
    expect(screen.getByText("Error:")).toBeInTheDocument();
    expect(screen.getByText("Payment failed, please retry.")).toBeInTheDocument();
  });

  it("renders a JSX child exactly as it renders a text child", () => {
    render(
      <Alert type="info">
        Your order <strong>#1234</strong> has been packed.
      </Alert>,
    );
    expect(screen.getByText("Info:")).toBeInTheDocument();
    expect(screen.getByText("#1234")).toBeInTheDocument();
    expect(screen.getByText(/has been packed\./)).toBeInTheDocument();
  });
});

solutions/ex03_chat_message.jsx

// Exercise 3 solution: three independent slots, the same shape as the
// lesson's PageSection - `avatar` and `timestamp` carry JSX just like
// `children` does, and ChatMessage never needs to know what either one
// contains.

export function ChatMessage({ avatar, children, timestamp }) {
  return (
    <div className="chat-message">
      <div className="chat-avatar">{avatar}</div>
      <div className="chat-body">{children}</div>
      <div className="chat-timestamp">{timestamp}</div>
    </div>
  );
}

solutions/ex03_chat_message.test.jsx

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

describe("ChatMessage", () => {
  it("renders avatar, body and timestamp from three independently-filled slots", () => {
    render(
      <ChatMessage
        avatar={<span aria-label="Ravi Shetty">RS</span>}
        timestamp={<time>10:42 AM</time>}
      >
        Your package has left the warehouse.
      </ChatMessage>,
    );

    expect(screen.getByLabelText("Ravi Shetty")).toHaveTextContent("RS");
    expect(
      screen.getByText("Your package has left the warehouse."),
    ).toBeInTheDocument();
    expect(screen.getByText("10:42 AM")).toBeInTheDocument();
  });
});

solutions/ex04_sort_cheapest_first.jsx

// Exercise 4 solution. The broken version given in exercises.md was:
//
//   function sortCheapestFirst(items) {
//     return items.sort((a, b) => a.price - b.price);
//   }
//
// MenuScreen called `sortCheapestFirst(menuItems)` just to build a "cheapest
// picks" banner, while a `FullMenuList` further down the same screen kept
// rendering the very same `menuItems` array in its original, chef-chosen
// order. Because `.sort()` mutates in place, building the banner silently
// reordered the full menu underneath it too - a bug with no error and no
// warning, exactly Part 2's "props are read-only" point.
//
// Fix: copy before sorting, so the shared array is never touched.

export function sortCheapestFirst(items) {
  return [...items].sort((a, b) => a.price - b.price);
}

solutions/ex04_sort_cheapest_first.test.jsx

import { describe, expect, it } from "vitest";
import { sortCheapestFirst } from "./ex04_sort_cheapest_first.jsx";

describe("sortCheapestFirst (fixed)", () => {
  it("returns a cheapest-first list without reordering the chef's original menu array", () => {
    const menuItems = [
      { name: "Paneer Butter Masala", price: 260 },
      { name: "Dal Makhani", price: 220 },
      { name: "Jeera Rice", price: 120 },
    ];
    const originalOrder = menuItems.map((item) => item.name);

    const banner = sortCheapestFirst(menuItems);

    expect(banner.map((item) => item.name)).toEqual([
      "Jeera Rice",
      "Dal Makhani",
      "Paneer Butter Masala",
    ]);
    // FullMenuList, rendered later from the same `menuItems` prop, still
    // sees the chef's original order - the bug this exercise fixes.
    expect(menuItems.map((item) => item.name)).toEqual(originalOrder);
  });
});

solutions/ex05_ride_receipt_breakup.jsx

// Exercise 5 solution: the same proof as the lesson's
// 04_breaking_up_ui.jsx, applied to a new domain - a cab ride receipt
// instead of a store invoice - to show the "split, don't rewrite" move is
// not specific to one kind of screen.

export function RideReceiptMonolith({ riderName, fare, distanceKm, driverName }) {
  return (
    <section className="ride-receipt">
      <div className="ride-header">
        <h3>{riderName}</h3>
        <p>{`Driver: ${driverName}`}</p>
      </div>
      <p className="ride-distance">{`${distanceKm} km`}</p>
      <div className="ride-footer">
        <p>{`Fare: ₹${fare.toLocaleString("en-IN")}`}</p>
      </div>
    </section>
  );
}

function RideHeader({ riderName, driverName }) {
  return (
    <div className="ride-header">
      <h3>{riderName}</h3>
      <p>{`Driver: ${driverName}`}</p>
    </div>
  );
}

function RideDistance({ distanceKm }) {
  return <p className="ride-distance">{`${distanceKm} km`}</p>;
}

function RideFooter({ fare }) {
  return (
    <div className="ride-footer">
      <p>{`Fare: ₹${fare.toLocaleString("en-IN")}`}</p>
    </div>
  );
}

export function RideReceipt({ riderName, fare, distanceKm, driverName }) {
  return (
    <section className="ride-receipt">
      <RideHeader riderName={riderName} driverName={driverName} />
      <RideDistance distanceKm={distanceKm} />
      <RideFooter fare={fare} />
    </section>
  );
}

solutions/ex05_ride_receipt_breakup.test.jsx

import { renderToStaticMarkup } from "react-dom/server";
import { describe, expect, it } from "vitest";
import {
  RideReceipt,
  RideReceiptMonolith,
} from "./ex05_ride_receipt_breakup.jsx";

const props = {
  riderName: "Priya Nair",
  fare: 184,
  distanceKm: 6.2,
  driverName: "Suresh Kumar",
};

describe("RideReceipt vs RideReceiptMonolith", () => {
  it("render byte-for-byte identical HTML", () => {
    const monolith = renderToStaticMarkup(<RideReceiptMonolith {...props} />);
    const composed = renderToStaticMarkup(<RideReceipt {...props} />);
    expect(composed).toBe(monolith);
  });

  it("still contains every real piece of data once split up", () => {
    const html = renderToStaticMarkup(<RideReceipt {...props} />);
    expect(html).toContain("Priya Nair");
    expect(html).toContain("Driver: Suresh Kumar");
    expect(html).toContain("6.2 km");
    expect(html).toContain("Fare: ₹184");
  });
});

solutions/ex06_product_grid.jsx

// Exercise 6 solution: the lesson's roadmap promise, made explicit - one
// ProductCard, reused three ways, now driven by data instead of three
// separate hand-written JSX tags. ProductGrid reuses the exact same
// ProductCard component the lesson's example already proved correct,
// instead of writing a fourth version of the same markup.

import { ProductCard } from "../examples/01_product_card.jsx";

export function ProductGrid({ products }) {
  return (
    <div className="product-grid">
      {products.map((product) => (
        <ProductCard key={product.name} {...product} />
      ))}
    </div>
  );
}

solutions/ex06_product_grid.test.jsx

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

describe("ProductGrid reuses ProductCard three ways from one array", () => {
  it("renders a plain, a discounted, and an out-of-stock product correctly", () => {
    render(
      <ProductGrid
        products={[
          { name: "Atta 5kg", price: 260, imageAlt: "A 5kg bag of atta" },
          {
            name: "Toor Dal 1kg",
            price: 140,
            imageAlt: "A 1kg packet of toor dal",
            discountPercent: 20,
          },
          {
            name: "Ghee 500ml",
            price: 320,
            imageAlt: "A 500ml jar of ghee",
            inStock: false,
          },
        ]}
      />,
    );

    expect(screen.getByText("Atta 5kg")).toBeInTheDocument();
    expect(screen.getByText("₹260")).toBeInTheDocument();

    expect(screen.getByText("₹112")).toBeInTheDocument();
    expect(screen.getByText("20% off")).toBeInTheDocument();

    expect(screen.getByRole("button", { name: "Out of stock" })).toBeDisabled();
    expect(screen.getAllByRole("button", { name: "Add to cart" })).toHaveLength(2);
  });
});

Common mistakes

Mistake Why it is wrong Fix
props.name, props.price, ... everywhere Works, but reads worse the moment a component has more than one or two props Destructure in the parameter list: function Card({ name, price })
inStock = false as the default for an "in stock" flag Silently marks every product that forgot to pass this prop as out of stock Default optimistically for flags like this (inStock = true), and be deliberate about which direction a missing boolean should fall
Checking header && <header>... with a value that could be 0 or "" 0 or an empty string is falsy, but is not "missing" the way undefined is - this is the "0 renders as text" trap, now on the other side of the condition Use ?? (nullish coalescing) or an explicit != null check when a slot's value could legitimately be 0 or ""
Calling .sort(), .push(), .splice(), or assigning into an index of a prop array All of these mutate the array in place - the parent's data changes with no error and no warning (section 5) Copy first - [...array] - before sorting, pushing, or otherwise changing it
Splitting a component "because it's long," with no named concept behind the split Produces oddly-shaped pieces with awkward prop lists that do not reuse and do not read any better Split along one of section 6's four signals - repetition, a nameable concept, an independent prop list, or wanting to test a piece alone
One mega-component for an entire page, "to keep it simple" The opposite extreme - everything shares one giant prop list, and nothing can be tested or reused on its own Apply section 6's signals early, even before the component feels unmanageably big

Quick recap

  • A prop is a component's one argument, an object; destructure it in the parameter list, the same way you would destructure any other function argument.
  • Give a prop a default value (= true, = 0, ...) for anything a caller might reasonably skip; leave the genuinely required props without one, since this course has no type system to enforce them for you.
  • children is whatever sits between a component's tags - the simplest, most common composition slot.
  • A component can expose more than one slot by accepting JSX through any other prop, named whatever makes sense (header, footer, left, avatar, ...).
  • Props are read-only: read from them freely, but never mutate an array or object a prop points to - .sort()/.push() and friends mutate in place and will silently change the parent's own data.
  • Splitting a UI into components should never change what renders - only how the code reads - and the four signals (repetition, a named concept, an independent prop list, wanting to test a piece alone) say when it is worth doing.

Checklist

  • I wrote a component that destructures its props in the parameter list, with at least one default value for a prop a caller can skip.
  • I can explain the difference between a required prop (no default, a convention) and a prop with a default value, and why this course cannot enforce "required" without TypeScript.
  • I wrote a component that accepts children and renders whatever is passed, without caring what it is.
  • I wrote a component with at least one named JSX slot that is not children (like header or footer).
  • I can reproduce, on purpose, a bug caused by mutating a prop (not just recite "props are read-only" as a rule), and fix it by copying first.
  • I split one of my own components into smaller, named pieces and confirmed - the same way renderToStaticMarkup did here - that the rendered output did not change.
  • I reused the same component with at least three different sets of props, the way this part's ProductCard was reused.

Search the guide