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

Part 01 / Stage 1

How React runs

Goal: Scaffold a project with Vite, explain JSX vs HTML, explain what a component is and why React re-renders, and run the dev server well enough to read its error overlay instead of fearing it. Time: ~3 hours · Level: comfortable with modern JS and HTML, new to React

What you will learn

  • What React actually is, and the kind of problem it solves that plain DOM code does not
  • How to scaffold a real project with npm create vite@latest ... -- --template react
  • What the five files Vite hands you are for, and what each one actually does
  • The syntax differences between JSX and HTML, and why each one exists
  • What JSX really compiles to underneath - plain createElement calls, nothing magic
  • What a component is: a function that takes props and returns JSX, and how components compose
  • What "re-render" means in concrete terms: React calling your function again
  • How to read Vite's dev-server error overlay instead of panicking at it

A note on how this part is organised: this repo's examples/ and solutions/ files are the verified reference code for this course - every one of them is wired into this repo's own harness/ (a shared Vite + Vitest setup, see TOOLING.md) and actually executed before being shown here. That harness is tooling for writing the course, not something you need. When you build along with this lesson, scaffold your own small project the way section 2 shows, the same way every part from here on expects you to - typing the code yourself in your own dev server is most of the point.

Topics in this part

Practice

Exercises 2–7 are React components (.jsx), each paired with a .test.jsx that actually renders it with Testing Library - the same verified-output rule as every example in this course. Exercise 1 has no component; its "output" is a real terminal transcript.


Exercise 1: Scaffold your own project

Scenario: Every part in this course expects you to type the lesson's code into a project you scaffolded yourself, not just read this repo's examples/. What to do: In a folder outside this repo (npm installs only ever happen inside react-step-by-step's own harness for this course's verification, never for your own practice project):

  1. Run npm create vite@latest my-first-react-app -- --template react.
  2. cd my-first-react-app && npm install.
  3. Run npm run dev, open the printed URL, and confirm the default Vite + React page loads.
  4. Run npm run build once, even though you have not changed anything yet.

Sample output: (abbreviated; your own package counts/timings will vary slightly - that is expected and marked (varies) in this course's convention)

$ npm create vite@latest my-first-react-app -- --template react
create-vite v9.4.0
Done. Now run:
  cd my-first-react-app
  npm install
  npm run dev

$ npm install
added 24 packages, and audited 25 packages in 7s (varies)
found 0 vulnerabilities

$ npm run build
vite v8.4.0 building client environment for production...
✓ 20 modules transformed.
✓ built in 538ms (varies)

💡 Hint: if npm run dev prints "Port 5173 is in use," either stop whatever else is using it or let Vite pick the next free port - it will tell you which one.


Exercise 2: Fix the broken program

Scenario: A teammate pastes you this component for an order-tracking screen. It does not render anything, and it is not obvious why.

export function OrderBadge({ status }) {
  return
    <div class="badge">
      <span>{status}</div>
    </div>
}

What to do: Find and fix every bug so <OrderBadge status="Packed" /> renders the word "Packed" with no console warnings.

What actually happens with each bug, left in on its own (really run, React 19.3.1):

  • return followed by a line break before the JSX: renders nothing at all, with no error - this is the one to watch for, because nothing tells you it is wrong.
  • class="badge" instead of className: renders fine, but the real browser console shows Invalid DOM property 'class'. Did you mean 'className'?.
  • <span>...</div> (mismatched closing tag): a real compile error, Expected corresponding JSX closing tag for 'span'.

💡 Hint: fix one bug at a time and re-render after each fix - the three bugs produce three different kinds of feedback (silent, a warning, and a hard error), which is itself worth noticing.


Exercise 3: Write your first component from scratch

Scenario: Meera's General Store wants a small receipt component for its billing screen. What to do: Write ReceiptCard({ shopName, items, total }), where items is an array of { name, qty, price }. Render the shop name, one line per item as "<name> x<qty> - ₹<qty * price>", and a total line as "Total: ₹<total, with en-IN digit grouping>".

Sample output (rendered with shopName="Meera General Store", items=[{name:"Atta 5kg",qty:1,price:260},{name:"Toor Dal 1kg",qty:2,price:140}], total=540):

Meera General Store
Atta 5kg x1 - ₹260
Toor Dal 1kg x2 - ₹280
Total: ₹540

💡 Hint: .map() over items to build a line per item, same as plain JS - Part 4 covers rendering lists properly (keys, especially); for now, a key on each <li> is enough to stop React's console from warning about a missing key.


Exercise 4: Composition for a new domain

Scenario: The lesson's Panel/WalletSummary pattern (a small reusable wrapper, reused by a bigger component) needs to work for completely different data to prove it is not wallet-specific. What to do: Write StatusTile({ label, children }) - a small reusable tile with a label and whatever is passed as children - and OrderTimeline({ packedOn, shippedOn, deliveredOn }) that renders three StatusTiles: "Packed", "Shipped", "Delivered". If deliveredOn is missing, show "Not yet" instead of leaving it blank.

Sample output (rendered with packedOn="12 Jan", shippedOn="13 Jan", deliveredOn="15 Jan"):

Packed
12 Jan
Shipped
13 Jan
Delivered
15 Jan

And with deliveredOn left out:

Delivered
Not yet

💡 Hint: deliveredOn ?? "Not yet" - the nullish-coalescing operator from the root README's prerequisites, not a React-specific trick.


Exercise 5: Prove your own component compiles to createElement

Scenario: Section 5 proved this for greetingViaJsx. Prove it for a component of your own. What to do: Write a small status badge, statusBadgeViaJsx(status) and statusBadgeViaCreateElement(status), the same shape as the lesson's two greeting functions. Render both with renderToStaticMarkup and assert the HTML is identical.

Sample output (status="Out for delivery", actually run):

<span class="status-badge">Out for delivery</span>

Both functions produce this exact string. 💡 Hint: createElement(tag, propsObject, ...children) - a single string child is enough here; you do not need an array.


Exercise 6: Reproduce and fix a real compile error

Scenario: The README showed a classpath-style error happening during this lesson's own writing. Now make a different real error happen to you, on purpose, and read what it actually says. What to do:

  1. Write SeatLabel({ seat }) that returns two sibling lines, <p>Seat</p> and <p>{seat}</p>, without wrapping them in anything, and with return on its own line above the JSX (both bugs at once).
  2. Run it through the harness (import it from a .test.jsx the way every other example does) and copy the exact error into a comment at the top of your file.
  3. Fix both bugs - return ( on one line, and a fragment <>...</> around the two <p> tags - and copy the passing result into the same comment.

Sample output (really produced by vitest run against the broken file, React/Vite transform, this exact message):

Error: Transform failed with 1 error:

[PARSE_ERROR] Adjacent JSX elements must be wrapped in an enclosing tag.
   ...
   Help: Did you want a JSX fragment `<>...</>`?

  Plugin: vite:oxc

💡 Hint: the "Help" line in oxc's own error names the fix. Compilers that tell you the fix in the error message are worth reading slowly, not skimming past.


Exercise 7: Prove a re-render is the function running again

Scenario: The lesson proved this with a Clock. Prove it with a cab-fare display, where the number actually needs to change, not just a label. What to do: Write FareDisplay({ fare }) with a module-level renderCount (same deliberate, not-for-real-code pattern as the lesson - see Part 1, section 7's oxlint note), incremented on every call, rendering "Render #<n>: fare ₹<fare>". Render it once, then re-render it twice more with different fares, and show the render count really reaches 3.

Sample output (really run: render with fare={120}, re-render with fare={150}, re-render again with fare={150}):

Render #1: fare ₹120
Render #2: fare ₹150
Render #3: fare ₹150

💡 Hint: the last two renders have the same fare on purpose - the point is that React re-ran the function a third time regardless, because it was asked to, not because the data changed. (Why React sometimes skips unnecessary re-renders is React.memo's job, taught properly in Stage 3's performance part - not needed here.)

Show the solutions for Part 1 (13 files)

solutions/ex01_scaffold_log.txt

Exercise 1 solution: a real scaffold-and-build transcript.

Run outside this repo (npm installs only happen inside react-step-by-step,
so this exercise used a throwaway /tmp folder, deleted right after):

$ npm create vite@latest my-first-react-app -- --template react
> npx
> 'cva' my-first-react-app --template react


create-vite v9.4.0

|
o  Scaffolding project in /private/tmp/ex1-scaffold/my-first-react-app...
|
`  Done. Now run:

  cd my-first-react-app
  npm install
  npm run dev

$ cd my-first-react-app
$ npm install
added 24 packages, and audited 25 packages in 7s

9 packages are looking for funding
  run `npm fund` for details

found 0 vulnerabilities

$ npm run build

> [email protected] build
> vite build

vite v8.4.0 building client environment for production...
transforming...
v 20 modules transformed.
rendering chunks...
computing gzip size...
dist/index.html                   0.46 kB | gzip:  0.30 kB
dist/assets/react-CHdo91hT.svg    4.12 kB | gzip:  2.06 kB
dist/assets/vite-BF8QNONU.svg     8.70 kB | gzip:  1.60 kB
dist/assets/hero-CLDdwZDr.png    13.05 kB
dist/assets/index-DykytF2W.css    4.10 kB | gzip:  1.47 kB
dist/assets/index-CwOdOtxP.js   221.92 kB | gzip: 69.16 kB

v built in 538ms

Three real things this proves:
1. `npm create vite@latest <name> -- --template react` needs no answers typed
   in (the --template flag skips the interactive prompts) and produces a
   project with no TypeScript, no CRA, matching this course's scope.
2. `npm install` really downloads only 24 packages for a bare React 19 + Vite
   project - there is no hidden framework weight here.
3. `npm run build` is a real compile step, not just a file copy: it bundles,
   transforms JSX, and reports a gzip size, before you have written a single
   line of your own code.

(The box-drawing characters create-vite prints - a box character before
"Scaffolding" and an L-shaped corner before "Done" - did not survive being
pasted into this plain-text file; they are replaced with "|", "o" and "`"
above. The real terminal output uses Unicode box-drawing glyphs.)

solutions/ex02_order_badge.jsx

// Exercise 2 solution. Three bugs, found and fixed one at a time (see
// exercises.md for what each one actually did when run):
// 1. `return` followed by a line break, then JSX on the next line - fixed by
//    putting the opening `(` right after `return`.
// 2. `class="badge"` - fixed to `className="badge"`.
// 3. `<span>...</div>` - mismatched closing tag - fixed to `</span>`.

export function OrderBadge({ status }) {
  return (
    <div className="badge">
      <span>{status}</span>
    </div>
  );
}

solutions/ex02_order_badge.test.jsx

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

describe("OrderBadge (fixed)", () => {
  it("renders the status text, unlike the broken version which rendered nothing", () => {
    render(<OrderBadge status="Packed" />);
    expect(screen.getByText("Packed")).toBeInTheDocument();
  });
});

solutions/ex03_receipt_card.jsx

// Exercise 3 solution: a component built from scratch, the same shape as
// the lesson's ProfileCard - a function that takes props and returns JSX.
// Lists in React are covered properly in Part 4; `.map()` here is plain
// JavaScript, just enough to loop over `items` without that lesson yet.

export function ReceiptCard({ shopName, items, total }) {
  return (
    <article className="receipt-card">
      <h3>{shopName}</h3>
      <ul>
        {items.map((item) => (
          <li key={item.name}>
            {`${item.name} x${item.qty} - ₹${item.price * item.qty}`}
          </li>
        ))}
      </ul>
      <p>{`Total: ₹${total.toLocaleString("en-IN")}`}</p>
    </article>
  );
}

solutions/ex03_receipt_card.test.jsx

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

describe("ReceiptCard", () => {
  it("renders the shop name, each line item and the total", () => {
    render(
      <ReceiptCard
        shopName="Meera General Store"
        items={[
          { name: "Atta 5kg", qty: 1, price: 260 },
          { name: "Toor Dal 1kg", qty: 2, price: 140 },
        ]}
        total={540}
      />,
    );

    expect(screen.getByText("Meera General Store")).toBeInTheDocument();
    expect(screen.getByText("Atta 5kg x1 - ₹260")).toBeInTheDocument();
    expect(screen.getByText("Toor Dal 1kg x2 - ₹280")).toBeInTheDocument();
    expect(screen.getByText("Total: ₹540")).toBeInTheDocument();
  });
});

solutions/ex04_order_timeline.jsx

// Exercise 4 solution: the same composition idea as the lesson's
// Panel/WalletSummary, reused for a different domain. StatusTile knows
// nothing about orders; OrderTimeline is the only thing that does.

function StatusTile({ label, children }) {
  return (
    <div className="status-tile">
      <h4>{label}</h4>
      <div>{children}</div>
    </div>
  );
}

export function OrderTimeline({ packedOn, shippedOn, deliveredOn }) {
  return (
    <div className="order-timeline">
      <StatusTile label="Packed">{packedOn}</StatusTile>
      <StatusTile label="Shipped">{shippedOn}</StatusTile>
      <StatusTile label="Delivered">{deliveredOn ?? "Not yet"}</StatusTile>
    </div>
  );
}

export { StatusTile };

solutions/ex04_order_timeline.test.jsx

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

describe("OrderTimeline composes StatusTile three times", () => {
  it("shows a date for each completed step", () => {
    render(
      <OrderTimeline packedOn="12 Jan" shippedOn="13 Jan" deliveredOn="15 Jan" />,
    );
    expect(screen.getByText("Packed")).toBeInTheDocument();
    expect(screen.getByText("12 Jan")).toBeInTheDocument();
    expect(screen.getByText("Shipped")).toBeInTheDocument();
    expect(screen.getByText("13 Jan")).toBeInTheDocument();
    expect(screen.getByText("Delivered")).toBeInTheDocument();
    expect(screen.getByText("15 Jan")).toBeInTheDocument();
  });

  it("falls back to 'Not yet' when a step has no date", () => {
    render(<OrderTimeline packedOn="12 Jan" shippedOn="13 Jan" deliveredOn={undefined} />);
    expect(screen.getByText("Not yet")).toBeInTheDocument();
  });
});

describe("StatusTile on its own", () => {
  it("renders whatever label and children it is given", () => {
    render(<StatusTile label="Returned">Pickup scheduled</StatusTile>);
    expect(screen.getByText("Returned")).toBeInTheDocument();
    expect(screen.getByText("Pickup scheduled")).toBeInTheDocument();
  });
});

solutions/ex05_badge_createelement.jsx

// Exercise 5 solution: the same proof as the lesson's
// 01_jsx_and_createElement.jsx, for a new component - a small coloured
// badge used on a delivery app's order list.

import { createElement } from "react";

export function statusBadgeViaJsx(status) {
  return <span className="status-badge">{status}</span>;
}

export function statusBadgeViaCreateElement(status) {
  return createElement("span", { className: "status-badge" }, status);
}

solutions/ex05_badge_createelement.test.jsx

import { renderToStaticMarkup } from "react-dom/server";
import { describe, expect, it } from "vitest";
import {
  statusBadgeViaCreateElement,
  statusBadgeViaJsx,
} from "./ex05_badge_createelement.jsx";

describe("statusBadge: JSX and createElement produce the same output", () => {
  it("renders identical HTML either way", () => {
    const viaJsx = renderToStaticMarkup(statusBadgeViaJsx("Out for delivery"));
    const viaCreateElement = renderToStaticMarkup(
      statusBadgeViaCreateElement("Out for delivery"),
    );
    expect(viaJsx).toBe(viaCreateElement);
    expect(viaJsx).toBe(
      '<span class="status-badge">Out for delivery</span>',
    );
  });
});

solutions/ex06_seat_label.jsx

// Exercise 6 solution. The broken version was:
//
//   export function SeatLabel({ seat }) {
//     return
//       <p>Seat</p>
//       <p>{seat}</p>
//   }
//
// Running it through the harness (any example that imports a broken file
// hits this the moment Vite/Vitest transforms it) gave this real error:
//
//   Error: Transform failed with 1 error:
//
//   [PARSE_ERROR] Adjacent JSX elements must be wrapped in an enclosing tag.
//      |-[ __probe5.jsx:4:5 ]
//      |
//    4 |     <p>{seat}</p>
//      |     +--
//      |     `--
//      |
//      | Help: Did you want a JSX fragment `<>...</>`?
//      --------
//
//     Plugin: vite:oxc
//
// Two separate problems were hiding in that one error:
// 1. `return` followed by a line break swallows the JSX below it (see Part
//    1, section 4) - the two <p> tags were never going to be returned at
//    all, broken or not.
// 2. Even once `return (` is fixed, two sibling <p> tags cannot be returned
//    side by side - JSX requires exactly one root node. Oxc's own "Help"
//    line names the fix: a fragment, `<>...</>` (Part 1, section 4).
//
// Fixed version:

export function SeatLabel({ seat }) {
  return (
    <>
      <p>Seat</p>
      <p>{seat}</p>
    </>
  );
}

solutions/ex06_seat_label.test.jsx

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

describe("SeatLabel (fixed)", () => {
  it("renders both lines now that they are wrapped in a fragment", () => {
    render(<SeatLabel seat="12A" />);
    expect(screen.getByText("Seat")).toBeInTheDocument();
    expect(screen.getByText("12A")).toBeInTheDocument();
  });
});

solutions/ex07_fare_render_tracker.jsx

// Exercise 7 solution: the same proof as the lesson's 04_render_counter.jsx
// - a module-level counter shows the component function really runs again
// on every re-render - applied to a cab-fare display instead of a clock.
// Same deliberate caveat as the lesson file: oxlint correctly warns that
// reassigning a variable declared outside the component during render is a
// side effect (`react(globals)`). Fine for this proof; never for real code.

let renderCount = 0;

export function resetRenderCount() {
  renderCount = 0;
}

export function getRenderCount() {
  return renderCount;
}

export function FareDisplay({ fare }) {
  renderCount += 1;
  return <p>{`Render #${renderCount}: fare ₹${fare}`}</p>;
}

solutions/ex07_fare_render_tracker.test.jsx

import { render, screen } from "@testing-library/react";
import { beforeEach, describe, expect, it } from "vitest";
import {
  FareDisplay,
  getRenderCount,
  resetRenderCount,
} from "./ex07_fare_render_tracker.jsx";

describe("FareDisplay re-renders when the fare prop changes", () => {
  beforeEach(() => {
    resetRenderCount();
  });

  it("runs the function again on every rerender, in the same order as the props change", () => {
    const { rerender } = render(<FareDisplay fare={120} />);
    expect(screen.getByText("Render #1: fare ₹120")).toBeInTheDocument();

    rerender(<FareDisplay fare={150} />);
    expect(screen.getByText("Render #2: fare ₹150")).toBeInTheDocument();

    rerender(<FareDisplay fare={150} />);
    expect(screen.getByText("Render #3: fare ₹150")).toBeInTheDocument();
    expect(getRenderCount()).toBe(3);
  });
});

Common mistakes

Mistake Why it is wrong Fix
class="card" in JSX class is a reserved JS word; React warns and ignores it className="card"
return then a line break before the JSX JavaScript's automatic semicolon insertion turns this into return; - the component silently renders nothing, with no error at all keep return ( on the same line as the opening parenthesis
Two sibling root elements, no wrapper JSX compiles to one function call per return; it cannot describe two elements at once wrap in a single parent, or an empty <>...</> fragment when no extra DOM element is wanted
Mismatched closing tag (<span>...</div>) the JSX parser needs an exact matching closer, like a stack of brackets fix the closing tag to match the one that opened it
Treating a component like a template with {{ }} (Vue/Angular habit) JSX only has single braces, {expr}, and only for JavaScript expressions, not statements use {expr}; push if/for logic above the return, not inside the JSX
Expecting the dev-server overlay to be a separate "React error" system it is the same compiler error Vite would print to the terminal anyway, just rendered in the browser read the file name and line number in the overlay; the fix is usually exactly there
Treating npm run build as only a "final step" it is the same compiler the dev server uses, so it is a fast way to confirm a file is even valid before you go looking for a runtime bug run it any time something feels wrong, not only before deploying

Quick recap

  • React is a UI library: you describe what the UI should look like now, and React patches the real DOM to match.
  • npm create vite@latest <name> -- --template react scaffolds a plain-JS React 19 project; npm run dev starts the dev server, npm run build is the production compile.
  • index.html has nothing but an empty <div id="root">; src/main.jsx mounts your component tree into it.
  • JSX looks like HTML but is JavaScript: className not class, camelCase event names, one root node per return (or a fragment), {} for any JS expression.
  • JSX compiles to plain createElement/jsx() calls that build element objects - not markup, not DOM nodes - and every {} value is escaped automatically.
  • A component is a function that takes props and returns JSX; composition is components calling components, with children as just another prop.
  • A re-render is React calling your component function again, in full - that is the entire mechanism, before any hook makes it useful.
  • The dev-server error overlay shows you the exact same compiler error the terminal would print; read the file and line number first.

Checklist

  • I scaffolded a React project myself with npm create vite@latest ... -- --template react, ran npm install, and started npm run dev.
  • I can say what index.html, src/main.jsx and src/App.jsx are each responsible for.
  • I can list at least four syntax differences between JSX and HTML and explain why each one exists.
  • I can explain, without looking it up, that JSX compiles to createElement/jsx() calls and that {} values are escaped automatically.
  • I wrote my own component that takes props and returns JSX, and reused it with different props.
  • I can explain what "re-render" means in terms of a function being called again, not in vague words like "updates."
  • I deliberately broke a file while the dev server was running, read the real error overlay, and fixed it.

Search the guide