# Tech Team (FA26)

# Overview

# Tech Team Fall 2026

Tech Team helps you get ready to work on a Blueprint project team. You don't need to know how to code before joining. We'll start with a small web page and work up to building a site together.

Along the way, you'll practice reading code, figuring out why something broke, and reviewing someone else's changes. Those are things you'll keep doing on a project team, even after you've learned the tools.

## When and where

We meet Wednesdays from 3 to 4 PM in EAS 230.

Join the Discord so you don't miss meeting updates. I'll put it in Discord if a meeting is canceled.

[Discord Invite](https://discord.gg/NFHdkyczVJ)

## What we'll cover

We'll begin with HTML, CSS, and JavaScript. You'll use them to build a personal page and make it respond to a button click. Then we'll learn Git and GitHub so you can save your work and make changes with other people.

After that, we'll use React to build reusable parts of a page. We'll add lists and search, learn how a page requests data from another service, and build a cart. Each lesson has code you can run and change.

Here's the plan. We can spend an extra meeting on a topic if we need more practice.

| Week | Topic | What you will do |
| --- | --- | --- |
| 1 | [HTML and CSS](https://wiki.sitblueprint.com/books/tech-team-fa26/page/week-1) | Build and style a personal page from blank files. |
| 2 | [JavaScript](https://wiki.sitblueprint.com/books/tech-team-fa26/page/week-2) | Make a button change the page and work through an error. |
| 3 | [Git and GitHub](https://wiki.sitblueprint.com/books/tech-team-fa26/page/week-3) | Save and publish your code, work on a branch, and practice a pull request review. |
| 4 | React | Build reusable components and pass information to them with props. |
| 5 | Lists and state | Display a list from data and use state to remember search text. |
| 6 | APIs | Request data and handle loading, errors, and empty results. |
| 7 | A shopping cart | Choose a product option and add, change, or remove items in a practice cart. |
| 8 | Checkout and orders | Follow a store cart into hosted checkout and understand how payment and orders fit together. |
| 9 | Project introduction | Join the shared repository, agree on how the parts connect, and start assigned tasks. |
| 10 | Building together | Build, review, and combine the teams' work. Repeat this meeting as needed. |
| 11 | Testing and presenting | Test the full flow, check a production build, and demonstrate what works. |


## Our project

We'll build a Blueprint merch site together in React. A visitor should be able to browse products, choose a size, add items to a cart, change the quantity, and go to checkout.

The site will use Fourthwall for product information and the store cart. Fourthwall will host checkout and handle payment and orders. We'll start with its catalog products, which its fulfillment network prepares and ships.

Everyone will contribute to the same repository. We'll split into teams, assign small tasks through GitHub issues, and review changes before combining them. This gives you practice working on one part of a site while other people work on the rest.

The earlier exercises use made-up data. For the project, we'll connect to the real store and test the full flow, including failed requests and what the page looks like on a phone.

## Before you come

Follow the [setup instructions](https://wiki.sitblueprint.com/books/tech-team-fa26/page/setup) and open that week's lesson. If you get stuck during setup or a lesson, ask for help. Weeks 1 and 2 have a temporary browser-editor fallback. From Week 3 onward, we'll use desktop VS Code and its terminal.

# Setup

Bring a laptop and charger. Try these steps before the meeting so we can spend the hour writing code. If you get stuck, come anyway and we can help you set things up.

## Before Week 1

We need an editor to write code and a browser to see what it does. We'll use VS Code as the editor.

1. Download [Visual Studio Code](https://code.visualstudio.com/download) for your computer and install it. Open it once to make sure it works.
2. Create a folder called `practice-page`, somewhere you can find it again. Documents is fine.
3. In VS Code, open **File > Open Folder** and select `practice-page`.
4. Save [avatar.svg](https://wiki.sitblueprint.com/attachments/17) in that folder. If the link opens the picture, use your browser's Save As option. Keep the filename `avatar.svg`.

This picture is the only file you need before Week 1. We will create the HTML and CSS files during the meeting. You can use your usual browser to open the page.


## Before Week 3

This week, we will use Git from VS Code and its terminal. We will sign in with GitHub CLI, turn the `practice-page` folder into a repository, save its first version, and publish it from VS Code. Do not create a repository or upload the files on GitHub beforehand. We will do that together.

### Install Git and GitHub CLI

VS Code has a Source Control view, but it uses Git installed on your computer. GitHub CLI, whose command is `gh`, will connect Git on your computer to your GitHub account.

1. Follow the [Git installation instructions](https://git-scm.com/downloads) for your operating system. On Windows, keep the installer's default choices. On macOS, run `git --version` and accept the developer tools installation if macOS asks.
2. Follow the [GitHub CLI installation instructions](https://github.com/cli/cli#installation) for your operating system.
3. Close and reopen VS Code after both installations.
4. Open the `practice-page` folder in VS Code. Choose **Terminal > New Terminal**.
5. Enter both commands, pressing Enter after each one:

```sh
git --version
gh --version
```

Each command should show a version number. If the terminal says it cannot find `git` or `gh`, restart your computer and try once more. Bring the error to the meeting if it still does not work.

### Tell Git who you are

Git stores a name and email with each commit. In the VS Code terminal, replace the example values below with your own name and an email connected to your GitHub account:

```sh
git config --global user.name "Your Name"
git config --global user.email "yourname@stevens.edu"
git config --global init.defaultBranch main
```

Git will use this name and email for your commits on this computer. The last command makes new repositories start with a branch named `main`. To check what you saved, run:

```sh
git config --global --get user.name
git config --global --get user.email
```

Your commit email can be visible in a public repository. If you do not want to use a personal address, copy the no-reply address from your [GitHub email settings](https://github.com/settings/emails) and use it in the second command.

### Sign in through GitHub CLI

1. [Create a free GitHub account](https://github.com/signup) if you do not have one. Verify the email and sign in.
2. In the VS Code terminal, run these commands:

```sh
gh auth login --hostname github.com --git-protocol https --web
gh auth setup-git
gh auth status
```

The first command opens a browser so you can approve the sign-in. Return to the VS Code terminal when it finishes. The second command tells Git to use that sign-in when you clone, push, or pull. The last command should show your GitHub username and say that you are logged in to `github.com`.

3. In VS Code, open **Extensions** and install [GitHub Pull Requests](https://marketplace.visualstudio.com/items?itemName=GitHub.vscode-pull-request-github), published by GitHub. This extension may ask for its own account connection when we create a pull request. Git itself will still use the account shown by `gh auth status`.
4. Open your Week 2 page and try the button. The folder should contain `index.html`, `styles.css`, `script.js`, and `avatar.svg`. Use the [Week 2 example](downloads/week-02-reference.zip) if you need a copy.
5. Find a partner and exchange GitHub usernames. You will invite each other after the repositories are published during the meeting.

Desktop VS Code is required for this meeting because vscode.dev does not have a terminal or access to Git on your computer. If you cannot install VS Code, Git, or GitHub CLI, come anyway and work beside a partner. We will arrange time to help you finish your own setup.

The [VS Code Git quickstart](https://code.visualstudio.com/docs/sourcecontrol/quickstart), [GitHub CLI login guide](https://cli.github.com/manual/gh_auth_login), and [Git credential setup guide](https://cli.github.com/manual/gh_auth_setup-git) cover these steps.

## Before Week 4

This week, we will keep using the `practice-page` repository and add a React project inside it. The React project needs Node.js and npm. npm downloads the code the project depends on, and Node.js runs the tools that start and check the page.

React runs the page's interface in the browser. This starter uses Vite to process JSX and serve the files during development. Node.js runs those tools on your computer; npm installs their packages and runs commands. We are not setting up a custom store backend. The [Week 4 lesson](lessons/week-04-react.md#how-this-project-reaches-the-browser) explains the files after you open the starter.

### Install Node.js

1. Download and install the current **LTS** version from the [Node.js download page](https://nodejs.org/en/download/). LTS is the version recommended for most people.
2. Close and reopen VS Code after the installation.
3. Open the `practice-page` folder in VS Code. Choose **Terminal > New Terminal**.
4. Run both commands:

```sh
node --version
npm --version
```

Each command should show a version number. The supplied starter accepts Node `v20.19.0` through the rest of the `v20` line, or `v22.12.0` and newer. Installing the current LTS release is the easiest way to meet that requirement. Update Node if your version is older, and bring any error message to the meeting if one of the commands does not work.

### Add the React starter

1. Download the [Week 4 starter](https://wiki.sitblueprint.com/attachments/20) and extract the ZIP.
2. Move the extracted `react-page` folder into `practice-page`. You should have `practice-page/react-page` when you finish.
3. Keep `practice-page` open in VS Code. A terminal runs commands inside a current folder. A new VS Code terminal normally starts in the folder you opened. `cd react-page` means “change directory”: enter the `react-page` folder inside the current one. `cd ..` moves up one folder. If you are unsure where you are, `pwd` shows the path in macOS, Linux, or PowerShell; `cd` by itself shows it in Windows Command Prompt. Start at `practice-page` and run:

```sh
cd react-page
npm install
npm run dev
```

4. Open the **Local** address shown in the terminal. You should see the React starter page.
5. Return to the terminal and press Ctrl+C to stop the development server.
6. Run `cd ..` so the terminal returns to the top of `practice-page`.

Do not initialize another Git repository inside `react-page`. The existing `practice-page` repository will track the React files. Do not commit the starter before the meeting; we will create a branch and save the changes together.

Desktop VS Code is required because this meeting uses the terminal, Node.js, and Git. If your setup does not work, come anyway and work beside a partner.

# Week 1

This week, we're starting with HTML and CSS. We'll use them to build a personal page with a heading, a picture, and some information about ourselves. We'll keep working on this page over the next few weeks, adding JavaScript and learning how to share changes through GitHub.

Later, we'll use what we've learned to build one shared Blueprint merch site. Teams will receive different tasks for that site. A product page needs a name, a picture, and a description, so a lot of what we do today will also apply there.

![week-01-preview.png](https://wiki.sitblueprint.com/uploads/images/gallery/2026-09/week-01-preview.png)

This is the page we'll be making. You can replace the example's name and interests with your own as we go.

## HTML and CSS

HTML describes the content and structure of a web page. It tells the browser which text is a heading, which text belongs in a paragraph, and where to place an image. CSS controls how that content looks, including its colors, font, and spacing.

[![image.png](https://wiki.sitblueprint.com/uploads/images/gallery/2026-09/scaled-1680-/image.png)](https://wiki.sitblueprint.com/uploads/images/gallery/2026-09/image.png)

For example, if we wanted to add a button to our page, we would use HTML to create the button and give it a label. We could then use CSS to change its color. Next week, we'll use JavaScript to make something happen when a button is clicked.

## Getting started

If you haven't set up your editor yet, follow the [setup checklist](https://wiki.sitblueprint.com/books/tech-team-fa26/page/setup). It also has a browser option if you can't install the editor.

1. Create a folder called `<span class="editor-theme-code">practice-page</span>` somewhere you can find again.
2. Open the folder in your editor and create two empty files, `<span class="editor-theme-code">index.html</span>` and `<span class="editor-theme-code">styles.css</span>`.
3. Save the supplied [avatar image](https://wiki.sitblueprint.com/attachments/17) into that folder as `<span class="editor-theme-code">avatar.svg</span>`. If the link opens the picture, use the browser's save option or ask for help downloading it.

The file endings matter. `<span class="editor-theme-code">index.html</span>` contains our HTML, and `<span class="editor-theme-code">styles.css</span>` contains our CSS. Make sure the editor hasn't added `<span class="editor-theme-code">.txt</span>` to either name.

When you edit a file, you need to save it before the browser can see your changes. Then refresh the browser to reload the saved version.

An HTML document has a `<span class="editor-theme-code">head</span>` and a `<span class="editor-theme-code">body</span>`. The `<span class="editor-theme-code">head</span>` contains information about the page, while the `<span class="editor-theme-code">body</span>` contains what people will see. Add this to `<span class="editor-theme-code">index.html</span>`:

```html
<!doctype html>
<html lang="en">
  <head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>My first page</title>
    <link rel="stylesheet" href="styles.css">
  </head>
  <body>
  </body>
</html>
```

Here, `<span class="editor-theme-code">title</span>` sets the text on the browser tab. The `<span class="editor-theme-code">link</span>` line tells the browser to load `<span class="editor-theme-code">styles.css</span>`, which is still empty. We'll add to it once we have some content on the page.

The other lines tell the browser how to read the document. `<span class="editor-theme-code"><!doctype html></span>` tells it to read the document as modern HTML, and `<span class="editor-theme-code">lang="en"</span>` says that the page is in English. `<span class="editor-theme-code">charset="utf-8"</span>` helps the browser read our letters, punctuation, and other text characters correctly. The viewport line makes the layout use the screen's width on mobile devices.

Save the file and open it in a browser. You should see a blank page with "My first page" on the tab. The page is blank because we haven't put anything inside the `<span class="editor-theme-code">body</span>` yet.

## HTML elements

HTML uses tags to describe content. For example, `<span class="editor-theme-code"><p></span>` begins a paragraph, and `<span class="editor-theme-code"></p></span>` ends it. The tags and the content between them make up an HTML element. The slash tells us which tag is the closing one.

We'll start with a heading and a paragraph. Add the following between `<span class="editor-theme-code"><body></span>` and `<span class="editor-theme-code"></body></span>`:

```html
<main>
  <h1>Hello, I'm Alex</h1>
  <p>I'm a student at Stevens.</p>
</main>
```

In this example, `<span class="editor-theme-code">main</span>` identifies the page's main content. Inside it, `<span class="editor-theme-code">h1</span>` marks the main heading, and `<span class="editor-theme-code">p</span>` marks a paragraph. The spaces at the start of the lines make it easier to see that the heading and paragraph are inside `<span class="editor-theme-code">main</span>`.

Headings also describe how the page is organized. We use `<span class="editor-theme-code">h1</span>` for the main heading, then `<span class="editor-theme-code">h2</span>` for headings within that page. This is helpful for screen readers, which read pages aloud. Someone using one can move between sections by their headings. If we want a heading to look different, we can change its CSS while keeping the right heading level.

Change Alex to your name, then save and refresh. You should see the heading change. Show the person next to you which part of the HTML you edited.

### Images and links

An image needs a little more information than a paragraph. We have to tell the browser where to find the image and provide text that describes it. Add this after the paragraph, before `<span class="editor-theme-code"></main></span>`:

```html
<img src="avatar.svg" alt="A blue smiling face" width="120" height="120">
<p>I like video games and photography.</p>
```

The extra information inside the opening tag is called an attribute. `<span class="editor-theme-code">src</span>` gives the image's location. Since `<span class="editor-theme-code">avatar.svg</span>` is in the same folder as `<span class="editor-theme-code">index.html</span>`, we can use its filename. `<span class="editor-theme-code">width</span>` and `<span class="editor-theme-code">height</span>` set its dimensions.

The `<span class="editor-theme-code">alt</span>` attribute provides a text alternative for the image. A screen reader can read it aloud, and the browser can display it if the image doesn't load. If you use a different picture, update this description to match. Unlike a paragraph, `<span class="editor-theme-code">img</span>` doesn't need a closing tag.

We can also add a link to another page. After the new paragraph, still before `<span class="editor-theme-code"></main></span>`, add:

```html
<a href="https://developer.mozilla.org/en-US/docs/Learn_web_development">MDN web development docs</a>
```

The `<span class="editor-theme-code">a</span>` element creates a link, and `<span class="editor-theme-code">href</span>` gives its destination. The words between the tags are what someone clicks. Here, the link takes us to MDN. It explains what HTML elements and CSS properties do and gives code examples. Giving the link a descriptive name helps someone know where it goes before opening it.

Save and refresh again. You should have a heading, two paragraphs, a picture, and a link. Try opening the link, then use the browser's Back button to return. Replace the interests sentence with something about yourself.

## CSS

So far, the browser has chosen the default font and spacing for our HTML. We can change those by writing CSS rules in `<span class="editor-theme-code">styles.css</span>`. Each rule selects part of the page and gives it a set of styles.

Open `<span class="editor-theme-code">styles.css</span>` and add:

```css
body {
  font-family: system-ui, sans-serif;
  background: #eef2ff;
  color: #172554;
  margin: 0;
  padding: 24px;
}
```

Here, `<span class="editor-theme-code">body</span>` is the selector. It tells the browser which element the rule applies to. Inside the braces, `<span class="editor-theme-code">{</span>` and `<span class="editor-theme-code">}</span>`, we write a property followed by its value. For example, in `<span class="editor-theme-code">color: #172554;</span>`, `<span class="editor-theme-code">color</span>` is the property and `<span class="editor-theme-code">#172554</span>` is the value. The colon separates them, and the semicolon marks the end.

This rule uses a system font, gives the page a pale background, and makes the text dark blue. The values beginning with `<span class="editor-theme-code">#</span>` are color codes. `<span class="editor-theme-code">margin: 0</span>` removes the body's default outside space, while `<span class="editor-theme-code">padding: 24px</span>` adds space inside it. This keeps the content away from the edge of the browser window. `<span class="editor-theme-code">px</span>` means CSS pixels, the units we're using for these sizes.

Save your files and refresh the browser. You should see the new colors and spacing. If the page still looks the same, check that the HTML links to `<span class="editor-theme-code">styles.css</span>` and that both files are in the same folder.

We can give `<span class="editor-theme-code">main</span>` its own styles as well. Add this below the first rule:

```css
main {
  max-width: 600px;
  margin: 0 auto;
  background: white;
  padding: 24px;
  border-radius: 16px;
}
```

Now the content sits inside a white card. `<span class="editor-theme-code">max-width</span>` stops the content area from becoming wider than 600 pixels. `<span class="editor-theme-code">margin: 0 auto</span>` gives it no top or bottom margin and uses automatic left and right margins to center it when there is room. The padding creates space inside the card, and `<span class="editor-theme-code">border-radius</span>` rounds its corners.

Try changing the padding in this rule from `<span class="editor-theme-code">24px</span>` to `<span class="editor-theme-code">48px</span>`. Before you refresh, think about which space should get larger. Compare the result, then change it back to `<span class="editor-theme-code">24px</span>`.

We can style the individual elements too. Add these rules below the others:

```css
h1 {
  color: #1d4ed8;
}

img {
  border-radius: 16px;
}

a {
  color: #1d4ed8;
}
```

The `<span class="editor-theme-code">h1</span>` rule changes the heading's color, the `<span class="editor-theme-code">img</span>` rule rounds the image's corners, and the `<span class="editor-theme-code">a</span>` rule changes the link's color. Each selector affects its matching element. If you changed the color in the `<span class="editor-theme-code">h1</span>` rule, would the paragraphs change too?

Keep the supplied colors for now. The dark text is readable against the pale and white backgrounds. Light text on a light background would be harder to read.

## Finding answers

Let's say we want the heading's text to be centered, but we want the paragraphs to stay as they are. We know where the heading's styles go, but we haven't learned which CSS property changes text alignment.

Search Google for `<span class="editor-theme-code">CSS center text W3Schools</span>` and open a result from `<span class="editor-theme-code">w3schools.com</span>`. Look for the property that controls text alignment and the value that centers it. Then add that property and value to the existing `<span class="editor-theme-code">h1</span>` rule in your CSS.

Save and refresh to see whether it worked. Only the heading's text should be centered. Compare your change with someone nearby and explain why you added it to `<span class="editor-theme-code">h1</span>`. If search isn't working, use the [W3Schools CSS text-align reference](https://www.w3schools.com/cssref/pr_text_text-align.php). You can also use the [MDN text-align reference](https://developer.mozilla.org/en-US/docs/Web/CSS/Reference/Properties/text-align) if you want a more detailed explanation.

You can use this approach whenever you need a property you haven't seen before. Start with the change you want to make, look for an example on W3Schools, and try it in your page. If you need more detail about how or why something works, check MDN. Check what the code does before adding more of it.

## Common problems

When something doesn't look right, start with the last thing you changed. Fixing one thing at a time makes it easier to tell what caused the problem.

<table id="bkmrk-what-you-see-what-to"><colgroup><col></col><col></col></colgroup><tbody><tr><th>What you see

</th><th>What to check

</th></tr><tr><td>Old words or colors

</td><td>Save the edited file, then refresh the correct browser tab.

</td></tr><tr><td>Raw HTML text instead of a page

</td><td>Check that the file is named `index.html`, and open it in a browser.

</td></tr><tr><td>Content appears, but none of the styling does

</td><td>Match `href="styles.css"` to the exact filename and folder.

</td></tr><tr><td>A broken picture

</td><td>Check that `avatar.svg` sits beside `index.html` and matches `src`.

</td></tr><tr><td>One CSS rule does nothing

</td><td>Check its selector, colon, semicolons, and both braces.

</td></tr><tr><td>Strange text or links

</td><td>Check that quotes and opening and closing tags are paired.

</td></tr></tbody></table>

Before next week

Save your work and keep the entire `<span class="editor-theme-code">practice-page</span>` folder. Next week, we'll add a button and use JavaScript to make it respond when clicked.

If you have time left, add a section called "Something I want to build" using `<span class="editor-theme-code">h2</span>` and a paragraph. Give the heading its own CSS rule.

The [completed example](https://wiki.sitblueprint.com/attachments/18) is available if you want to compare files or need help catching up. It includes the centered heading from the search exercise.

## Resources

Start with W3Schools for examples and quick references. Use MDN when you want a more detailed explanation or additional technical information.

### W3Schools

- [W3Schools: HTML Introduction](https://www.w3schools.com/html/html_intro.asp)
- [W3Schools: HTML Headings](https://www.w3schools.com/html/html_headings.asp)
- [W3Schools: HTML Images](https://www.w3schools.com/html/html_images.asp)
- [W3Schools: CSS Syntax](https://www.w3schools.com/css/css_syntax.asp)
- [W3Schools: CSS Padding](https://www.w3schools.com/css/css_padding.asp)
- [W3Schools: CSS text-align](https://www.w3schools.com/cssref/pr_text_text-align.php)

### MDN

- [MDN: HTML and document structure](https://developer.mozilla.org/en-US/docs/Learn_web_development/Getting_started/Your_first_website/Creating_the_content)
- [MDN: Heading elements](https://developer.mozilla.org/en-US/docs/Web/HTML/Reference/Elements/Heading_Elements)
- [MDN: Images](https://developer.mozilla.org/en-US/docs/Web/HTML/Reference/Elements/img)
- [MDN: CSS rules and styling](https://developer.mozilla.org/en-US/docs/Learn_web_development/Getting_started/Your_first_website/Styling_the_content)
- [MDN: Padding](https://developer.mozilla.org/en-US/docs/Web/CSS/Reference/Properties/padding)
- [MDN: text-align](https://developer.mozilla.org/en-US/docs/Web/CSS/Reference/Properties/text-align)

</body></html>

# Week 2

Last week, we used HTML and CSS to build a personal page. HTML gave us the content, and CSS let us change how it looked. If we wanted to change the text on the page, we had to edit the HTML file and refresh the browser.

JavaScript is a programming language that lets us change a page while someone is using it. For example, we can respond to a button click by showing a message. We will add that to the same page we made last week.

Here is what our page will look like before and after clicking the button:

[![week-02-before.png](https://wiki.sitblueprint.com/uploads/images/gallery/2026-09/scaled-1680-/week-02-before.png)](https://wiki.sitblueprint.com/uploads/images/gallery/2026-09/week-02-before.png)

[![week-02-after.png](https://wiki.sitblueprint.com/uploads/images/gallery/2026-09/scaled-1680-/week-02-after.png)](https://wiki.sitblueprint.com/uploads/images/gallery/2026-09/week-02-after.png)

The button stays in the same place, and the paragraph underneath it changes. We can use similar code later when someone interacts with part of the merch page.

## Getting started

Open last week's folder in your editor and open `index.html` in your browser. Keep the editor and browser next to each other so you can see what happens as you work. If you missed last week or cannot find your files, ask for a copy of the Week 1 example.

## Adding the button

First, we need a button to click and a paragraph where we can show the fact. Add these inside `<main>`, just before `</main>`:

```html
<p><button id="fact-button" type="button">Show a fun fact</button></p>
<p id="fact" aria-live="polite">Your fact will appear here.</p>
```

The first line adds a button inside a paragraph, which keeps it on its own line. `type="button"` makes it a regular button. Because we used the HTML `<button>` element, the browser already lets someone reach it with the keyboard and activate it with Enter or Space.

The `id` attributes give these elements unique names on the page. Our button's ID is `fact-button`, and our message's ID is `fact`. JavaScript will use those IDs to find the right elements, so make sure each spelling matches the example.

A screen reader reads page content aloud. `aria-live="polite"` tells it to announce changes to the paragraph when it has finished what it is already reading. This is helpful because someone using a screen reader might otherwise miss the new message.

Save the file and refresh the page. You should see both elements, but clicking the button will not change anything yet. We still need to write the JavaScript that handles the click.

## Adding JavaScript to the page

Create a file called `script.js` in the same folder as `index.html` and `styles.css`. The `.js` ending tells us this is a JavaScript file.

In `index.html`, add the following line just before `</body>`:

```html
<script src="script.js"></script>
```

This tells the browser where to find our JavaScript. We put it at the end of the body so the browser reads the button and paragraph before running code that tries to find them. Save both files.

## Finding elements

To change one paragraph, JavaScript needs a way to find it on the page. The browser organizes the HTML elements into the Document Object Model, usually shortened to DOM. We can use the DOM to find our paragraph and change its text.

A program works with values, such as text, numbers, or elements from a page. A variable gives a value a name so we can use it later in our code. In this example, we want names for our button and paragraph.

Add these lines to `script.js`:

```js
const factButton = document.querySelector("#fact-button");
const fact = document.querySelector("#fact");
```

`document` refers to the current page. `querySelector` finds the first element that matches a selector. The selector tells it which element to look for. Here, `#` means an ID, so `"#fact-button"` finds the element with `id="fact-button"`.

`const` creates a variable and prevents us from giving it a different value later. The `=` gives the name on the left the value on the right. Here, `factButton` refers to the button that `querySelector` found. The semicolon ends the instruction.

The second line does the same thing for our paragraph, using the name `fact`. We can now use `factButton` and `fact` throughout the file without looking up the elements again.

Compare each selector with its HTML ID. Notice that the `#` appears in the JavaScript selector, but not in the HTML ID itself. Also, `factButton` is a name we chose for our variable. It does not have to be spelled the same way as the ID.

## Functions

Now that we have the paragraph, we need to describe what should happen to it. A function groups instructions under a name. Calling the function means telling it to run those instructions.

We will make a function called `showFact`. Add this below the two variables:

```js
function showFact() {
  fact.textContent = "I can solve a Rubik's Cube.";
}
```

`function` tells JavaScript we are defining a function, and `showFact` is its name. The instructions go inside the braces, `{` and `}`. The parentheses are empty because this function does not need us to give it any inputs.

Inside the function, `fact.textContent` refers to the text in our paragraph. The `=` replaces that text with the value on the right. Text inside quotation marks is called a string. Here, our string is `"I can solve a Rubik's Cube."`. The browser displays the sentence without the surrounding quotation marks.

Earlier, we used `const` for `fact`. We can still change the paragraph's text because `fact` continues to refer to the same element. We are changing that element's content, rather than giving the variable a different element.

At this point, we have described what `showFact` does, but we have not called it. If you refresh the page, the starting message will still be there.

## Events

An event is something that happens on a page, such as someone clicking a button. An event listener lets us run a function when a particular event happens.

We want `showFact` to run when someone clicks our button. Add this line below the function's closing brace:

```js
factButton.addEventListener("click", showFact);
```

In this example, we add the listener to `factButton`. `"click"` is the event we want to respond to, and `showFact` is the function we want to run.

Notice that we wrote `showFact` without parentheses here. That gives the listener a function it can call later. Writing `showFact()` would call the function immediately while the page loads, instead of giving the listener the function to use when someone clicks.

Save both files and refresh the page. Click the button. You should now see the fact appear. Here is the complete `script.js` so you can compare it with your file:

```js
const factButton = document.querySelector("#fact-button");
const fact = document.querySelector("#fact");

function showFact() {
  fact.textContent = "I can solve a Rubik's Cube.";
}

factButton.addEventListener("click", showFact);
```

Try clicking the button again, then refresh the page. Each click sets the same message. Refreshing brings back the starting text because our JavaScript changes the page in the browser, not the saved HTML file.

## Changing the message

Replace the fact with something about yourself. Change the words inside the double quotation marks in `showFact`, and keep the surrounding punctuation in place. You can also change the button's visible text in `index.html`. Keep the button's ID the same so the selector still finds it.

The screenshots also use button styles. If you want the same appearance, copy the two rules beginning with `button` to the end of your `styles.css`. They change how the button looks, and our JavaScript works with or without them.

## Debugging

Debugging means finding and fixing a problem in our code. Let's make a small mistake so we can see what the browser tells us about it.

In the first line of `script.js`, remove one `t` from `fact-button`:

```js
const factButton = document.querySelector("#fact-buton");
```

Save, refresh, and try clicking. The button is still there, but it no longer changes the message.

Right-click the page, choose **Inspect**, and open the **Console** tab. The console shows errors from JavaScript. Look for the error connected to `script.js`. Its wording may vary by browser, but you may see `null` and `addEventListener`.

`querySelector` returns `null` when it cannot find a matching element. Our HTML still has `id="fact-button"`, but our JavaScript now looks for `fact-buton`. As a result, `factButton` contains `null`, and the next part of our code cannot attach a listener to it.

The error points to the line where JavaScript tried to add the listener. The actual mistake is earlier, in the selector. Fix the missing `t`, save, and refresh. The button should work again.

If your code stops working, start with what you expected to happen and what happened instead. The console often gives you a place to look. Change one thing at a time so you can tell which change fixed the problem.

## Before next week

Before that meeting, follow the [Week 3 setup checklist](https://wiki.sitblueprint.com/books/tech-team-fa26/page/setup) to install Git and GitHub CLI, sign in from the VS Code terminal, and find a partner. Keep the page in its current folder. We will turn that folder into a repository and publish it together. If you cannot finish setup, come anyway, and we can figure it out.

## Resources

Start with W3Schools for a short example. Use MDN for more detail.

- [W3Schools: JavaScript Introduction](https://www.w3schools.com/js/js_intro.asp)
- [W3Schools: Functions](https://www.w3schools.com/js/js_functions.asp)
- [W3Schools: textContent](https://www.w3schools.com/jsref/prop_node_textcontent.asp)
- [MDN: What is JavaScript?](https://developer.mozilla.org/en-US/docs/Learn_web_development/Core/Scripting/What_is_JavaScript)
- [MDN: querySelector](https://developer.mozilla.org/en-US/docs/Web/API/Document/querySelector)
- [MDN: const](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/const)
- [MDN: Functions](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Functions)
- [MDN: textContent](https://developer.mozilla.org/en-US/docs/Web/API/Node/textContent)
- [MDN: addEventListener](https://developer.mozilla.org/en-US/docs/Web/API/EventTarget/addEventListener)
- [MDN: aria-live](https://developer.mozilla.org/en-US/docs/Web/Accessibility/ARIA/Reference/Attributes/aria-live)

# Week 3

Last week, we used JavaScript to make a button display a fun fact. So far, all of our work has lived in one folder on our own computer. This week, we will start saving that work with Git and sharing it through GitHub.

We will use two parts of VS Code. The Source Control view shows our changed files and gives us buttons for common Git actions. The terminal lets us give Git commands directly. Both work with the same folder and the same history.

We will still open the page in a browser to test it. Our code stays in VS Code, and we will publish it through Source Control.

By the end of this hour, your local `<span class="editor-theme-code">main</span>` branch should be published and a second branch should contain one tested, pushed change. We will also walk through a pull request and partner review. If your pair needs more time for that part, use the review steps below to finish it during catch-up before the shared project starts in Week 9.

## Git and GitHub

Git is a version control system. It records versions of our files so we can see what changed over time. If a button stops working, that history can help us find the change that caused the problem.

A project stored with Git is called a repository, or repo. Each saved version is called a commit. A commit contains the changes we chose and a short message that explains them.

GitHub stores Git repositories online so other people can work with us. Git records the history on our computer. GitHub gives the team a shared copy of that history.

The copy on GitHub is called a remote repository. Git usually gives the main remote the short name `<span class="editor-theme-code">origin</span>`. Pushing sends local commits to the remote. Pulling brings remote commits back to our computer.

[![image.png](https://wiki.sitblueprint.com/uploads/images/gallery/2026-10/scaled-1680-/image.png)](https://wiki.sitblueprint.com/uploads/images/gallery/2026-10/image.png)

## Opening the terminal

Open the `<span class="editor-theme-code">practice-page</span>` folder in desktop VS Code. You should see `<span class="editor-theme-code">index.html</span>`, `<span class="editor-theme-code">styles.css</span>`, `<span class="editor-theme-code">script.js</span>`, and `<span class="editor-theme-code">avatar.svg</span>` in the Explorer.

Choose **Terminal &gt; New Terminal**. The terminal opens at the bottom of VS Code. A terminal lets us type commands for the computer to run. Type each command after the prompt and press Enter. Do not include the word `<span class="editor-theme-code">sh</span>` from the labels above the code blocks.

Start by checking that Git and GitHub CLI are available and that GitHub CLI knows which account to use:

```sh
git --version
gh --version
gh auth status
```

The first two commands should show version numbers. The last command should show your GitHub username and say that you are logged in to `<span class="editor-theme-code">github.com</span>`. If it does not, return to the [GitHub CLI setup](https://wiki.sitblueprint.com/setup.md#sign-in-through-github-cli) before continuing.

Next, check the name and email Git will store with your commits:

```sh
git config --global --get user.name
git config --global --get user.email
```

If either command shows nothing, return to the [Week 3 setup](https://wiki.sitblueprint.com/setup.md#tell-git-who-you-are) and add the missing value before continuing.

## Creating the repository

Select the **Source Control** icon on the left side of VS Code. It looks like a line with connected circles. Choose **Initialize Repository**.

Initializing creates Git's history inside the folder. It does not publish the files or change what the page looks like. You may notice letters beside the filenames in Source Control. `<span class="editor-theme-code">U</span>` means a file is untracked, so Git has not saved a version of it yet.

Return to the terminal and run:

```sh
git status
```

`<span class="editor-theme-code">status</span>` tells us which branch we are on and which files have changed. The four page files should appear under **Untracked files**. If you see files from outside `<span class="editor-theme-code">practice-page</span>`, stop and ask for help. Git may have been initialized in the wrong folder.

## Staging and committing the files

Before we make a commit, we choose which changes belong in it. This step is called staging. It stops us from saving an unrelated or unfinished change by accident.

In the Source Control view, find **Changes**. Select the plus button beside `<span class="editor-theme-code">index.html</span>`, `<span class="editor-theme-code">styles.css</span>`, `<span class="editor-theme-code">script.js</span>`, and `<span class="editor-theme-code">avatar.svg</span>`. Each file should move to **Staged Changes**.

Enter this message in the box at the top:

```text
Add my practice page
```

Select **Commit**. We now have a saved version in our local repository. Run these commands in the terminal:

```sh
git status
git log --oneline
```

`<span class="editor-theme-code">status</span>` should say there is nothing to commit. `<span class="editor-theme-code">log</span>` shows the commit we just made. The letters and numbers at the start of its line identify that commit.

## Creating the remote and publishing from VS Code

Our commit still exists only on this computer. First, use GitHub CLI to create a private repository on GitHub and connect it to this local repository:

```sh
gh repo create practice-page --private --source=. --remote=origin
git remote -v
```

`<span class="editor-theme-code">gh repo create</span>` creates the private remote repository. `<span class="editor-theme-code">--source=.</span>` means the repository in the current folder, and `<span class="editor-theme-code">--remote=origin</span>` connects the remote using the usual name `<span class="editor-theme-code">origin</span>`. We left out the `<span class="editor-theme-code">--push</span>` option, so the commit is still only on this computer.

Return to Source Control and select **Publish Branch**. If you do not see it, open the **...** menu and choose **Push**. Source Control uses the GitHub CLI credentials to upload the `<span class="editor-theme-code">main</span>` branch.

Run `<span class="editor-theme-code">git status</span>`. It should say that `<span class="editor-theme-code">main</span>` is up to date with `<span class="editor-theme-code">origin/main</span>`. You can open the repository address from `<span class="editor-theme-code">git remote -v</span>` to confirm the four files are there, but keep editing the local files in VS Code.

### Give your partner access

A private repository can only be opened by people you invite. This access setting is the one part we need to complete on GitHub's website.

Open the repository, choose **Settings &gt; Collaborators**, and invite your partner's GitHub username. Your partner should invite you to their repository too. Both people need to accept the invitation before the review. Copy the repository address shown by this terminal command and send it to your partner:

```sh
git remote get-url origin
```

## Making a branch

Our first commit is on a branch called `<span class="editor-theme-code">main</span>`. We will use `<span class="editor-theme-code">main</span>` for the version we have checked and agreed to keep.

A branch lets us work on a change separately. When we create a branch from `<span class="editor-theme-code">main</span>`, it starts with the same files. We can change the fun fact while `<span class="editor-theme-code">main</span>` keeps the original. Once someone has reviewed the change, we can merge it into `<span class="editor-theme-code">main</span>`.

Create a branch in the terminal:

```sh
git switch -c improve-fact
```

`<span class="editor-theme-code">switch</span>` moves us to another branch. The `<span class="editor-theme-code">-c</span>` option tells Git to create the branch first. The branch name appears in the lower-left corner of VS Code. You can also check it with:

```sh
git branch --show-current
```

It should say `<span class="editor-theme-code">improve-fact</span>`. The files still look the same because we have only created the branch.

## Changing and reviewing a file

Open `<span class="editor-theme-code">script.js</span>`. The Week 2 example used this line:

```js
fact.textContent = "I can solve a Rubik's Cube.";
```

Add a little more detail:

```js
fact.textContent = "I can solve a Rubik's Cube in under two minutes.";
```

If you wrote a different fact last week, add a detail to that one instead. Save the file, then run:

```sh
git status
git diff
```

`<span class="editor-theme-code">status</span>` should list `<span class="editor-theme-code">script.js</span>` as modified. `<span class="editor-theme-code">diff</span>` shows the exact lines that changed. A line beginning with `<span class="editor-theme-code">-</span>` is the old version, and a line beginning with `<span class="editor-theme-code">+</span>` is the new version. Red and green show removal and addition; they do not tell us whether the code is good or bad.

You can see the same comparison by selecting `<span class="editor-theme-code">script.js</span>` under **Changes** in Source Control. Read it before staging. Make sure only the sentence changed.

## Testing the branch

Open the same local `<span class="editor-theme-code">index.html</span>` you have been using. Click the button. The new sentence should appear. Click again to confirm it stays, then refresh and check that the starting message returns. The picture and styles should still load.

## Staging and committing in the terminal

This time, we will stage and commit with commands:

```sh
git add script.js
git diff --staged
git commit -m "Add the solving time to the Rubik's Cube fact"
```

`<span class="editor-theme-code">git add</span>` stages the file. After staging, plain `<span class="editor-theme-code">git diff</span>` no longer shows that change, so `<span class="editor-theme-code">git diff --staged</span>` shows what the next commit will contain.

The `<span class="editor-theme-code">-m</span>` option gives the commit its message. A message like `<span class="editor-theme-code">update</span>` tells us very little. Naming the change helps a teammate understand the commit without opening it.

Run `<span class="editor-theme-code">git status</span>` again. It should say the working tree is clean. The new commit is local until we push the branch:

```sh
git push -u origin improve-fact
```

`<span class="editor-theme-code">push</span>` sends the commit to GitHub. `<span class="editor-theme-code">origin</span>` identifies the remote repository, and `<span class="editor-theme-code">improve-fact</span>` identifies the branch. The `<span class="editor-theme-code">-u</span>` connects the local and remote branches, so later we can use the shorter command `<span class="editor-theme-code">git push</span>`.

## Creating a pull request in VS Code

We now have a change on `<span class="editor-theme-code">improve-fact</span>` that we want to add to `<span class="editor-theme-code">main</span>`. A pull request, usually shortened to PR, is how we propose that change on GitHub. Opening a PR does not change `<span class="editor-theme-code">main</span>`.

Select the GitHub icon in VS Code to open **GitHub Pull Requests**. The extension may ask you to connect a GitHub account the first time you open it. Choose the same account shown by `<span class="editor-theme-code">gh auth status</span>`. This connection lets the extension display pull requests; Git still uses GitHub CLI when it pushes and pulls.

Make sure the current branch is `<span class="editor-theme-code">improve-fact</span>`, then choose **Create Pull Request** and set the base branch to `<span class="editor-theme-code">main</span>`. The base receives the change from our current branch.

Read the diff and confirm it shows the sentence you meant to change. Use a title such as:

```text
Add the solving time to the Rubik's Cube fact
```

In the description, explain what changed and what happened when you tested it. For example:

> I added how long it takes to solve the Rubik's Cube. I opened the page from my improve-fact branch and tried the button. It showed the new sentence, and the picture and styles still loaded.

Write what you actually checked. Add your partner as the reviewer, then create the PR.

## Reviewing a pull request in VS Code

Your partner needs a local copy of your repository to try the change. Cloning downloads a repository, including its files and Git history.

1. Accept your partner's collaborator invitation.
2. In VS Code, open the Command Palette with **View &gt; Command Palette** and run **Git: Clone**.
3. Paste the HTTPS repository address your partner sent you. Git will use the account shown by `<span class="editor-theme-code">gh auth status</span>`.
4. Choose a parent folder that is separate from your own `<span class="editor-theme-code">practice-page</span>`. Open the cloned repository in a new VS Code window.
5. Select the GitHub Pull Requests icon, find the PR assigned to you, and open it.
6. Select **Checkout** on the PR. VS Code switches the local files to the branch from that PR.

Read the description and open **Changes in Pull Request**. Select `<span class="editor-theme-code">script.js</span>` to read the diff.

Open `<span class="editor-theme-code">index.html</span>` from the cloned folder and try the button. The sentence on the page should match the added line in the diff. If the change makes sense and works, describe what you checked and approve it. If something is unclear or broken, comment on the line or request a change. Submit the review so the author can see it.

You do not have to invent a problem. A useful approval says what you read and tested.

## Updating the pull request

If your reviewer asks for a change, return to your own `<span class="editor-theme-code">practice-page</span>` window. Make sure the lower-left corner says `<span class="editor-theme-code">improve-fact</span>`, then edit and test the file. Save another commit on the same branch:

```sh
git add script.js
git commit -m "Clarify the fun fact"
git push
```

The existing PR updates when the new commit reaches the same remote branch. Do not open another PR for the correction. Ask your partner to make sure the PR branch is checked out, run `<span class="editor-theme-code">git pull</span>` in that repository's terminal, and test it again.

## Merging and updating `<span class="editor-theme-code">main</span>`

Once the change works and your partner has approved it, return to your own `<span class="editor-theme-code">practice-page</span>` window. Open the PR description in VS Code and select **Merge**. Merging brings the branch's change into `<span class="editor-theme-code">main</span>` on GitHub.

Your local `<span class="editor-theme-code">main</span>` still needs that remote change. Return to the terminal in your own repository and run:

```sh
git switch main
git pull
```

Open `<span class="editor-theme-code">script.js</span>` and find the new sentence. Now the local and remote copies of `<span class="editor-theme-code">main</span>` both contain the reviewed change.

In Week 9, teams will receive different tasks in one shared merch repository. The repository will already exist, so you will clone it instead of publishing it. You will then use the same branch, commit, push, PR, review, merge, and pull steps from this lesson. Before that, we will learn React, product data, APIs, carts, and checkout through smaller examples.

## Before next week

Complete the [Week 4 setup](https://wiki.sitblueprint.com/books/tech-team-fa26/page/setup) before our next meeting. We will rebuild part of the practice page with React.

## Common problems

<table id="bkmrk-what-you-seewhat-to-"><colgroup><col></col><col></col></colgroup><tbody><tr><th>What you see

</th><th>What to check

</th></tr><tr><td>The terminal cannot find

`<span class="editor-theme-code">git</span>`

</td><td>Install Git, then completely close and reopen VS Code. Run

`<span class="editor-theme-code">git --version</span>`

 again.

</td></tr><tr><td>The terminal cannot find

`<span class="editor-theme-code">gh</span>`

</td><td>Install GitHub CLI, then completely close and reopen VS Code. Run

`<span class="editor-theme-code">gh --version</span>`

 again.

</td></tr><tr><td>`<span class="editor-theme-code">gh auth status</span>`

 says you are not logged in

</td><td>Repeat the

[GitHub CLI sign-in steps](https://wiki.sitblueprint.com/setup.md#sign-in-through-github-cli)

, then run

`<span class="editor-theme-code">gh auth status</span>`

 again.

</td></tr><tr><td>GitHub CLI shows the wrong account

</td><td>Run

`<span class="editor-theme-code">gh auth switch</span>`

. If the account you need is not listed, repeat the

[GitHub CLI sign-in steps](https://wiki.sitblueprint.com/setup.md#sign-in-through-github-cli)

. Then run

`<span class="editor-theme-code">gh auth setup-git</span>`

.

</td></tr><tr><td>A commit asks for your identity

</td><td>Run the two

`<span class="editor-theme-code">git config --global</span>`

 commands from setup with your own name and commit email.

</td></tr><tr><td>Source Control shows files outside

`<span class="editor-theme-code">practice-page</span>`

</td><td>Stop before committing. Check which folder is open in VS Code and ask for help finding where Git was initialized.

</td></tr><tr><td>`<span class="editor-theme-code">gh repo create</span>`

 says the repository already exists

</td><td>Stop before choosing another command. Check the existing repository with the facilitator so you do not overwrite or connect to the wrong project.

</td></tr><tr><td>**Publish Branch**

 is missing

</td><td>Run

`<span class="editor-theme-code">git remote -v</span>`

 and confirm that

`<span class="editor-theme-code">origin</span>`

 exists. Make sure the first commit is on

`<span class="editor-theme-code">main</span>`

, then look for

**Push**

 in the Source Control

**...**

 menu.

</td></tr><tr><td>The wrong sentence appears

</td><td>Run

`<span class="editor-theme-code">git branch --show-current</span>`

, save

`<span class="editor-theme-code">script.js</span>`

, and refresh the local page.

</td></tr><tr><td>The PR has nothing to compare

</td><td>Confirm you committed on

`<span class="editor-theme-code">improve-fact</span>`

 and pushed it. Run

`<span class="editor-theme-code">git status</span>`

 and

`<span class="editor-theme-code">git log --oneline</span>`

.

</td></tr><tr><td>A partner cannot clone the repository

</td><td>Check that the invitation was accepted by the account shown by

`<span class="editor-theme-code">gh auth status</span>`

, then run

`<span class="editor-theme-code">gh auth setup-git</span>`

 and try the HTTPS address again.

</td></tr><tr><td>The Pull Requests view shows the wrong account

</td><td>Sign out of that extension account and connect the same account shown by

`<span class="editor-theme-code">gh auth status</span>`

.

</td></tr><tr><td>`<span class="editor-theme-code">main</span>`

 still has the old sentence after merging

</td><td>Switch to

`<span class="editor-theme-code">main</span>`

, run

`<span class="editor-theme-code">git pull</span>`

, then reopen or refresh the file.

</td></tr></tbody></table>

## Resources

- [Install Git](https://git-scm.com/downloads)
- [Install GitHub CLI](https://github.com/cli/cli#installation)
- [GitHub CLI: Sign in](https://cli.github.com/manual/gh_auth_login)
- [GitHub CLI: Configure Git credentials](https://cli.github.com/manual/gh_auth_setup-git)
- [GitHub CLI: Create a repository](https://cli.github.com/manual/gh_repo_create)
- [VS Code: Source Control](https://code.visualstudio.com/docs/sourcecontrol/overview)
- [VS Code: Git quickstart](https://code.visualstudio.com/docs/sourcecontrol/quickstart)
- [VS Code: Repositories and remotes](https://code.visualstudio.com/docs/sourcecontrol/repos-remotes)
- [VS Code: Work with GitHub](https://code.visualstudio.com/docs/sourcecontrol/github)
- [Git: Recording changes](https://git-scm.com/book/en/v2/Git-Basics-Recording-Changes-to-the-Repository)
- [GitHub: Invite a collaborator](https://docs.github.com/en/repositories/managing-your-repositorys-settings-and-features/managing-repository-settings/inviting-collaborators-to-a-personal-repository)

If you forget a command, start with the result you need. For example, search Google for `<span class="editor-theme-code">GitHub CLI create repository from existing folder</span>` or `<span class="editor-theme-code">Git show current branch</span>`. Open a result from the VS Code, Git, or GitHub documentation and compare its example with your current folder and branch before running it.

# Week 4

Last week, we used Git to save our practice page and review a change. This week, we'll rebuild part of that page with React. By the end, you'll have one `InterestCard` component used twice with different text, plus a layout that fits a narrow or wide browser. We'll also try a button that changes a card title and follow what happens inside the page.

## Why are we using React?

In Week 2, we found a paragraph with `querySelector` and changed its `textContent`. That worked because we knew exactly which element needed different text.

Now think about our merch site. Choosing a size can change the price and whether a button is available. Adding an item can change its quantity in the cart and the displayed subtotal. We need those pieces to agree about the current data.

React is a JavaScript library for building user interfaces. A user interface is the part someone sees and uses, such as a product card or a size selector. With React, we describe what those parts should show for the current data. When that data changes through React, React calculates the next result and updates the browser's elements.

We divide the interface into components. A component is a reusable piece of the interface defined in code. In this lesson, our component is a JavaScript function that returns a description of one interest card. We can use it twice and give each card different information. Later, a `ProductCard` can work the same way for merch.

We can build this with plain JavaScript too. React gives us a common structure for the repeated, changing parts that our teams will work on. It also adds concepts, dependencies, and build tools. It does not make a page faster just because we used it. For a short information page with one button, I would usually keep the plain HTML, CSS, and JavaScript version.

React lets us describe what should appear for the current data. After we've built the title-changing button, we'll put plain JavaScript and React next to each other and follow the same change in both versions. That will make the word declarative more useful than a definition on its own.

| Job | Earlier page | React page |
| --- | --- | --- |
| Describe a card | Write HTML. | Return JSX from a component. JSX is HTML-like syntax inside JavaScript. |
| Style the card | Write CSS. | Keep writing CSS. Use `className` in JSX where HTML uses `class`. |
| Reuse the card | Copy markup or write a JavaScript function. | Use one component several times with different inputs, called props. |
| Change what is displayed | Find and change DOM elements. | Update state and let React calculate the result. State is information React remembers between renders. |
| Run the project | Open an HTML file. | Run Vite so it can process JSX and serve the files. |

## What is an element, and what is the DOM?

Start with the heading from our interest card:

```html
<h3>Video games</h3>
```

`<h3>` is the opening tag. `Video games` is the content. `</h3>` is the closing tag. Together, they describe an HTML heading element. A tag is one part of the markup for an element. An element such as `img` has no content or closing tag in HTML.

This picture labels the same parts of a paragraph:

<img src="https://developer.mozilla.org/en-US/docs/Learn_web_development/Core/Structuring_content/Basic_HTML_syntax/grumpy-cat-small.png" width="821" height="255" style="display:block;width:100%;max-width:821px;height:auto" alt="The paragraph has an opening p tag, the text My cat is very grumpy, and a closing p tag. The complete piece is the element.">

The browser turns HTML into a set of objects that represent the page. This is the DOM, or Document Object Model. JavaScript can find these objects, read them, and change them.

A **node** is one item in the DOM. It is a general name for several kinds of object. Two kinds matter in this example:

- An **element node** represents an element such as `h3` or `p`.
- A **text node** holds the words inside an element, such as `Video games`.

For `<h3>Video games</h3>`, the browser makes an `h3` element node and a separate text node holding `Video games`. The opening and closing tags describe the same element. They do not become two separate nodes.

Here is the whole card:

```html
<article class="interest-card">
  <h3>Video games</h3>
  <p>I like learning how games are designed.</p>
</article>
```

The `article` contains `h3` and `p` directly. We call `article` their **parent**, and `h3` and `p` its **children**. The `h3` is also the parent of the text node holding `Video games`. A child can have children of its own.

When we draw these connections, they branch. That is why we call this structure a **tree**. Each box below is one node. Each line connects a parent to a child:

<!-- lesson-image: dom-interest-card -->
<img src="https://wiki.sitblueprint.com/uploads/images/gallery/2026-10/dom-interest-card.png" alt="The article contains h3 and p element nodes, each with a text node. Setting textContent replaces the h3's Video games text node with a Board games text node. The h3 and p elements stay." style="display:block;width:100%;max-width:1200px;height:auto">

Three of the shown nodes are elements: `article`, `h3`, and `p`. The other two are text nodes. Every DOM element is a node because an element is one kind of node. A text node is also a node, but it is not an element.

The browser also makes text nodes for spaces and line breaks between tags. We leave those out of the picture so the card's structure is easier to see. You can read more in [MDN's Node reference](https://developer.mozilla.org/en-US/docs/Web/API/Node), but the two kinds above are enough for this exercise.

Week 2's `querySelector` returned a DOM element. For example, put the card markup above in a plain HTML page. After the card, add a `script` element containing this JavaScript, as we did in Week 2:

```js
const heading = document.querySelector(".interest-card h3");
heading.textContent = "Board games";
```

The selector finds the first `h3` inside an element with the class `interest-card`. `heading` refers to that live element. Assigning its `textContent` changes the text inside it. Setting `textContent` replaces the h3's text node with a new one; the `h3` element itself stays. The browser shows "Board games" and keeps the paragraph. The saved HTML file on disk still says "Video games". Changing the live page does not rewrite that file.

## Starting the React page

Open the whole `practice-page` repository in desktop VS Code. The React starter belongs in `practice-page/react-page`. Open a terminal in `react-page` and run `npm install` once before continuing.

Open the integrated terminal. The prompt usually shows the folder where commands will run; this is the current folder. Start at the top of `practice-page`. If you are inside `react-page`, run `cd ..` once: `cd` changes the current folder, and `..` means its parent folder. Then start a branch for this lesson:

```sh
git switch main
git pull
git status
git switch -c react-profile
```

Before the last command, `git status` should show no unfinished changes from earlier lessons. The new `react-page` folder may be listed if you have not saved it with Git yet. If it lists an unfinished change from another lesson, stop and ask for help.

Now move into the React folder and start the page. `cd react-page` enters that folder from `practice-page`:

```sh
cd react-page
npm run dev
```

The terminal will print a local address. It often starts with `http://localhost:`, followed by a port number. Open the exact address shown on your computer.

This command starts a development server. The server gives the browser the files React needs and watches them while we work. Keep this terminal running. When you save a React file, the browser should update.

The address is local to your computer. Running the development server does not publish the page online.

## How this project reaches the browser

The starter supplies a few files that connect our component to the page. Open them once so you know what they do. We will mainly edit `App.jsx`, the new `InterestCard.jsx`, and CSS today.


| File                | What it does in this starter                                                                                                     |
| ------------------- | -------------------------------------------------------------------------------------------------------------------------------- |
| `index.html`        | Contains a `div` with `id="root"` and loads `src/main.jsx`. This is inside `react-page`, separate from the original HTML lesson. |
| `src/main.jsx`      | Imports `App` and `styles.css`, then asks React to display `App` inside that root element. Leave its startup code in place.      |
| `src/App.jsx`       | Defines the component describing our practice page. This is where we will first change the heading.                              |
| `src/styles.css`    | Contains ordinary CSS for the page and cards.                                                                                    |
| `public/avatar.svg` | Contains the supplied image. Vite serves it at `/avatar.svg`.                                                                    |
| `package.json`      | Lists the project's packages and names commands such as `dev` and `build`.                                                       |


Follow the path from `index.html` to `main.jsx` to `App.jsx`. React uses the description returned by `App` to create the elements inside the root. The page still has HTML elements that you can inspect in the browser.

React and Vite have different jobs. React describes and updates the interface. Vite is the development and build tool in this starter; it processes JSX and serves the project locally. Node.js runs those tools on your computer, and npm installs packages and runs the named scripts. In this project, Node.js is not the shopper's browser or a custom store backend.

Saving `App.jsx` updates the local browser because of the development tools. That automatic update while editing is different from an event changing state while someone uses the finished page.

## React and JSX

We will write our components as JavaScript functions that return a description of part of the page. `return` gives a result back to the code that called the function. React calls our component and uses that result to decide what to show. Our Week 2 function changed an existing paragraph; this function gives React a description of the page.

Open `react-page/src/App.jsx`. `App` is the main component in this project. The `.jsx` ending tells us that the file contains JavaScript and JSX.

JSX lets us write HTML-like markup inside JavaScript. Most of the elements in `App.jsx` should look familiar from Week 1. There are a few differences:

- JSX uses `className` to assign a CSS class. A class is a label we can reuse on several elements to give them the same styles. Plain HTML calls this attribute `class`.
- Every tag must close. The image ends with `/>`.
- The JSX in this starter returns one outer element: `main`.
- Braces place a JavaScript value inside the markup.

The elements still have their HTML jobs. Our `h1`, `h2`, and `h3` describe the heading order, `article` groups one card, and `alt` describes the image. Keep the section's `aria-labelledby` connected to the heading's `id`. React does not make that work for us if we remove it. Attributes beginning with `aria-` or `data-` keep their dashes in JSX.

For an action, use a real `button`. The browser already knows how to focus it and activate it from the keyboard. Moving HTML into a component should preserve those behaviors.

Find this line:

```jsx
<h1>Hello, I'm Alex</h1>
```

Change Alex to your name or a nickname. Save the file and look at the browser. The heading should update without a manual refresh.

The development server saw the saved change and sent the changed code to the browser, which swapped it in without reloading the page. The saved code is still in `App.jsx`, just as our earlier page content was saved in `index.html`.

## Making a component

The interest card is currently written inside `App`. We'll move it into its own component. The page should look the same after the move.

Create a file named `InterestCard.jsx` inside `react-page/src`. Add this code:

```jsx
export default function InterestCard() {
  return (
    <article className="interest-card">
      <h3>Video games</h3>
      <p>I like learning how games are designed.</p>
    </article>
  );
}
```

`InterestCard` returns the JSX between the parentheses after `return`. The parentheses let that result span several lines. Keep the opening parenthesis on the same line as `return`, as shown. Component names start with a capital letter. Lowercase names such as `article`, `h3`, and `p` refer to HTML elements.

The words `export default` make this component available to another file.

Return to `App.jsx`. Remove the matching `article` from inside `interest-list`. At the top of the file, before the `App` function, add:

```jsx
import InterestCard from "./InterestCard.jsx";
```

`import` brings the component from `InterestCard.jsx` into this file. The `./` means the two files are in the same folder.

Inside `interest-list`, where the article used to be, add:

```jsx
<InterestCard />
```

Save both files. The card should return and look the same as it did before. `<InterestCard />` tells React to use the component we made.

We moved the card without changing its result. Giving the card its own component lets us reuse it.

## Passing props

If we add `<InterestCard />` twice now, both cards will show the same words. Props let one component give information to another component.

`App` uses `InterestCard`, so `App` is the parent component and `InterestCard` is its child component. The parent passes props to the child.

Replace the first line of `InterestCard.jsx` so the function receives a value named `props`:

```jsx
export default function InterestCard(props) {
```

`props` is the function's parameter: the name we use for the information it receives. React puts the values passed to a component into the `props` object. An object groups values under names. We will use the names `title` and `description`.

Replace the fixed heading and paragraph inside the component:

```jsx
export default function InterestCard(props) {
  return (
    <article className="interest-card">
      <h3>{props.title}</h3>
      <p>{props.description}</p>
    </article>
  );
}
```

The braces tell JSX to display a JavaScript value. `props.title` gets the value named `title`, and `props.description` gets the value named `description`.

The card will be blank until `App` passes those values. In `App.jsx`, replace `<InterestCard />` with:

```jsx
<InterestCard
  title="Video games"
  description="I like learning how games are designed."
/>
```

Save both files. The original card should appear again.

The prop name must match in both places. `title="Video games"` passes the value. `props.title` reads it, and `{props.title}` displays it.

Treat props as read-only inputs. To change this card's title, change the value that `App` passes. Do not assign a new value to `props.title` inside `InterestCard`.

### Quoted text or a JavaScript value?

What would `title="title"` display? It passes the literal word "title". Quotes do not ask JavaScript to look up a variable.

For a quick comparison, add this inside `App`, above its `return`:

```jsx
const title = "Board games";
```

Change the first card to use `title={title}`. The braces read the variable, so the card now receives "Board games". The same rule works with `description`, an image's `src`, and other props. Braces can contain an expression that produces a value, such as a variable or a calculation.

Try `title="title"`, then `title={title}`, and compare the headings. Restore the original title prop and remove the temporary variable before continuing. The reference keeps the original fixed strings.

## Reusing the component

Add a second card below the first one:

```jsx
<InterestCard
  title="Photography"
  description="I like taking pictures around Hoboken."
/>
```

Save the file. The page should show two cards with different words. Both use the code in `InterestCard.jsx`.

Change the two cards to describe your interests. Add a third `InterestCard` if you have another idea. Change the prop values in `App.jsx`; do not copy the component function.

Here is the complete `App.jsx` for comparison:

```jsx
import InterestCard from "./InterestCard.jsx";

export default function App() {
  return (
    <main>
      <h1>Hello, I'm Alex</h1>
      <p>I'm a student at Stevens.</p>
      <img
        className="profile-image"
        src="/avatar.svg"
        alt="A blue smiling face"
        width="120"
        height="120"
      />

      <section aria-labelledby="interests-heading">
        <h2 id="interests-heading">Things I like</h2>
        <div className="interest-list">
          <InterestCard
            title="Video games"
            description="I like learning how games are designed."
          />
          <InterestCard
            title="Photography"
            description="I like taking pictures around Hoboken."
          />
        </div>
      </section>
    </main>
  );
}
```

The merch project will use the same idea. A `ProductCard` component can contain the shared structure, while each use passes a different product's information.

## What happens when we click a button?

Let's say our card says "Video games". We want a button that changes it to "Board games". The button needs to do more than change a JavaScript variable. React also needs to know that it should calculate the page again. Code that should run because of a click goes in the click handler, not in the component body.

We now have two cards. Keep that version of `App.jsx` so you can restore it after this experiment. For example, copy it into an unsaved editor tab. Replace `App.jsx` with this complete file:

```jsx
import { useState } from "react";
import InterestCard from "./InterestCard.jsx";

export default function App() {
  const [title, setTitle] = useState("Video games");

  function handleClick() {
    setTitle("Board games");
  }

  return (
    <main>
      <h1>My interests</h1>
      <button type="button" onClick={handleClick}>
        Show board games
      </button>
      <section aria-labelledby="demo-heading">
        <h2 id="demo-heading">Things I like</h2>
        <InterestCard
          title={title}
          description="I like learning how games are designed."
        />
      </section>
    </main>
  );
}
```

Keep the `InterestCard.jsx` we already made. It reads `props.title` and `props.description` and returns an `article`, `h3`, and `p`.

`useState` lets a component keep information between renders. We import it from React because it is a React function. On the first render, `useState("Video games")` gives us two values. `title` is the current value, and `setTitle` is the function we call to request a different value. The square brackets give those two returned values separate names. This syntax is called array destructuring.

React remembers this state while this `App` stays in the same place in the component tree. On later renders, `useState` gives us the stored value. Calling `App` again does not start the title over. Keep `useState` at the top of the component, outside conditions, loops, and event handlers, so React can match each call with the same stored state. Reloading this page does start it over, because this example does not save state outside the running page.

The click is an event. An event is a notification that something happened, such as a click or a key press. `handleClick` is the event handler, the function we want React to call for this button's click. `onClick={handleClick}` passes the function. Adding parentheses, as in `onClick={handleClick()}`, would call it while calculating the page instead of waiting for the click.

Save `App.jsx`. The card should say "Video games". Click **Show board games**. The heading should become "Board games", and the paragraph should keep its original words. You do not need to refresh the browser.

### How the button works

<!-- lesson-image: react-click-update -->
<img src="https://wiki.sitblueprint.com/uploads/images/gallery/2026-10/react-click-update.png" alt="A click calls setTitle. React renders App and InterestCard, compares the result with the last one, commits only the h3 text change from Video games to Board games, and the browser paints it. The paragraph stays the same." style="display:block;width:100%;max-width:1200px;height:auto">
<br>

When the button is clicked, React runs your components again to work out what the page should show. This is called **rendering**. React calls `App`, then `InterestCard`, and `InterestCard` returns JSX for a heading and a paragraph. Returning JSX doesn't touch the page yet.

React then compares the new result with the old one. Here only the heading's text changed, so that's the only thing it updates in the real page. This step is called the **commit**, and it has nothing to do with Git commits. The browser then redraws the card. If the new heading is longer and wraps onto another line, the card can get taller too.

### Why not just use a normal variable?

You might think this would work:
```jsx
function App() {
  let title = "Video games";
  function handleClick() {
    title = "Board games"; // changes the variable...
  }
  return <InterestCard title={title} />;
}
    
```
It doesn't work, for two reasons. Changing `title` doesn't tell React to render again, so nothing on screen changes. And even if `App` did run again, the first line would reset `title` to "Video games".

`useState` fixes both problems. It remembers the value between renders, and its setter tells React to render again:

```jsx
const [title, setTitle] = useState("Video games");
function handleClick() {
  setTitle("Board games"); // asks React for a new render
}
```

One catch is that `setTitle` doesn't change `title` inside the click handler that's already running. It asks for the next render, and that render gets the new value.

`App` owns the state. `InterestCard` just receives the current title as a prop and reads `props.title`. It never changes its props itself.


### Declarative React beside plain JavaScript

You don't need to run these. Just compare them. Both start with "Video games" and change the heading to "Board games" when the button is clicked.

Plain JavaScript, like Week 2:

```html
<h1 id="interest-title">Video games</h1>
<button id="title-button" type="button">Show board games</button>

<script>
  const heading = document.querySelector("#interest-title");
  const button = document.querySelector("#title-button");

  button.addEventListener("click", () => {
    heading.textContent = "Board games";
  });
</script>
```

This is **imperative**. We find the heading ourselves and tell the browser exactly what to change. If the title showed up in three places, we'd have to update all three.

The same thing in React:

```jsx
const [title, setTitle] = useState("Video games");

return (
  <main>
    <h1>{title}</h1>
    <button type="button" onClick={() => setTitle("Board games")}>
      Show board games
    </button>
  </main>
);
```

This is **declarative**. `<h1>{title}</h1>` says "the heading always shows the current title," and we write that once. When we call `setTitle`, React renders again and updates the heading for us. There's no `querySelector` and no `textContent`.

For one heading, the plain version is perfectly fine. React starts to pay off when lots of parts of the page depend on the same data and all need to stay in sync.

[React's state guide](https://react.dev/learn/reacting-to-input-with-state) covers the same idea with more examples.

### What is React comparing?

JSX produces descriptions called React elements. For example, `<h3>{props.title}</h3>` describes a heading and its current text. A React element is a JavaScript value. It is not the live DOM object returned by `querySelector`.

`InterestCard` is the component function. `<InterestCard title={title} />` describes one use of that function, including its inputs. When React renders the component, it calls the function to get the elements inside the card.

This picture shows the state demo after the click, when `App` passes `title` as "Board games":

<!-- lesson-image: react-elements-to-dom -->
<img src="https://wiki.sitblueprint.com/uploads/images/gallery/2026-10/react-elements-to-dom.png" alt="The state demo after the click: the InterestCard component, the React elements it returns, and the live DOM, where the existing h3 now says Board games." style="display:block;width:100%;max-width:1200px;height:auto">

Here are the three meanings of element in this lesson:

| Place | What we are looking at |
| --- | --- |
| HTML source | `<h3>Video games</h3>` is markup describing a heading element. |
| Browser DOM | A live heading object, which `querySelector` can return. Its text can change. |
| React code | JSX produces a React element describing what React should display. |

This picture separates the component tree from the browser DOM tree:

<img src="https://react.dev/images/docs/diagrams/preserving_state_dom_tree.png" width="1726" height="384" style="display:block;width:100%;max-width:1200px;height:auto" alt="Component A has children B and C. React DOM connects that component tree to one branch of the browser's larger DOM tree.">

For our two-card page, imagine A is `App` and B and C are its two uses of `InterestCard`. Both cards use the same function. Each card returns several elements, so the component tree and the DOM tree have different jobs and different numbers of parts.

You'll hear people call this the **virtual DOM**. It's just React's description of what the page should look like, kept in memory. It isn't a second page. The real DOM is what the browser is actually showing, and React uses its description to figure out what needs to change there.

Comparing the old description with the new one is called **reconciliation**. React matches things up by what type of element they are and where they are. In our card, the `article`, `h3`, and `p` are all still in the same spots, so React keeps them and just swaps the heading's text. If an `h3` turned into an `input`, React would throw the old one away and make a new element.

The same goes for components. If a component disappears, or gets swapped for a different one in the same spot, React throws away its state. Next week we'll use keys to help React keep track of items in a list when they move around. We don't need them yet, because our two cards never move.

### The first render and later renders

The first time the page loads, `main.jsx` calls `root.render(<App />)`. React runs `App` and every component inside it, builds the real elements, and puts them on the page.

After that, every time state changes, React runs `App` again, along with the components inside it, even ones whose props didn't change. It compares the new result with the old one and only touches the parts of the page that actually changed. Sometimes nothing changed, and then React leaves the page alone.

One thing that might catch you, if you put a `console.log` inside a component, you might see it print twice. That's the starter's `StrictMode` running components twice on purpose while you develop, to catch bugs. It doesn't mean you clicked twice.

Not every change on the page goes through React:

| What you do | What happens |
| --- | --- |
| Save `App.jsx` while Vite is running | Vite sends your new code to the browser. |
| Click the button | The handler updates state, and React renders again. |
| Resize the window | The browser rearranges things with CSS. React doesn't run. |
| Reload the page | Everything starts over, so the title goes back to "Video games". |

Before moving on, put back the two-card `App.jsx` from **Reusing the component**. That's the version we keep for today. Next week we'll use what you just saw to make the cards change.

## How the cards get their styles

The starter still uses ordinary CSS. Open `src/styles.css` and find `.interest-card`. The dot means this rule selects a class, so it styles each element whose JSX says `className="interest-card"`. Unlike an ID, the same class can appear on several elements.

Now find the list rule:

```css
.interest-list {
  display: grid;
  gap: 12px;
}
```

The `div` with `className="interest-list"` groups the cards. `display: grid` lets CSS arrange its children in rows and columns. This rule uses one column, so every new card gets a row. `gap` adds space between them.

Try changing `gap` to `24px`. The space between cards should grow while the padding inside each card stays the same. Restore `12px` after checking it.

Now let the cards sit side by side when the browser has room. Add this after the closing brace of the existing `.interest-list` rule:

```css
@media (min-width: 600px) {
  .interest-list {
    grid-template-columns: 1fr 1fr;
  }
}
```

A media query applies CSS only when its condition is true. Here, `min-width: 600px` checks whether the browser's page area is at least 600 CSS pixels wide. It checks the browser width, not the width of the card. The rules inside its braces apply at that width and above.

`grid-template-columns` sets the columns. Each `1fr` asks for one equal share of the available space, so `1fr 1fr` makes two equal columns. Below 600 pixels, this rule stops applying and the original one-column grid remains. This is a responsive layout: the arrangement changes to fit the available space.

Save, then resize the browser. Check a narrow view around 390 pixels and a wide view around 900 pixels. Use the browser's device toolbar in **Inspect** if the window will not get narrow enough. You should see one column in the narrow view, two in the wide view, and space between the cards in both. The text should remain readable without horizontal scrolling.

A merch catalog can use the same technique for its product cards.

## A shorter way to read props

```jsx
export default function InterestCard({ title, description }) {
```

Then remove `props.` from the two values inside the JSX:

```jsx
<h3>{title}</h3>
<p>{description}</p>
```

Save and check the page. It should look the same. We changed how the component receives its props, not what it displays.

This syntax is called object destructuring. React still passes one props object. The braces select its `title` and `description` properties and give us variables with those names. `function InterestCard(props)` followed by `props.title` and `function InterestCard({ title })` followed by `title` read the same input. There is no new React behavior here.

An unknown prop is still `undefined`. Destructuring does not repair a misspelled prop name. You can keep the original `props.title` version if it is easier to follow.

## Debugging a prop

In the second card in `App.jsx`, change `description` to the misspelled name `descripton`:

```jsx
<InterestCard
  title="Photography"
  descripton="I like taking pictures around Hoboken."
/>
```

Save the file. The second heading remains, but its paragraph becomes blank.

`InterestCard` asks for a prop named `description`. The parent passed a different name, so `description` has no value to display. This mistake might not show a red error screen.

When part of a component is blank, compare the prop names where the component is used and where it receives them. Restore the missing `i`, save, and check that the paragraph returns.

If the browser shows an error screen, read its filename and line number. JSX errors often come from an unclosed tag, brace, quote, or parenthesis near that line.

## Saving the React page with Git

Open a second integrated terminal so the development server can keep running. The new terminal should start at the top of `practice-page`. If its prompt ends with `react-page`, run `cd ..` once before continuing.

First, run the React project's build check:

```sh
cd react-page
npm run build
cd ..
```

The build should finish without an error. A folder named `dist` will appear, but the project's `.gitignore` keeps it out of Git.

Run `git status`, then open **Source Control** in VS Code. Read the changed React files and use the plus buttons to stage them. If `react-page/package-lock.json` is listed, stage it too. It records the exact package versions so others install the same ones. Check the selection in the terminal:

```sh
git diff --staged --stat
git diff --staged -- react-page/src/App.jsx react-page/src/InterestCard.jsx
```

Read the staged files. `node_modules` and `dist` should not appear. `node_modules` contains packages downloaded by `npm install`; another person can restore them from `package-lock.json`.

If either ignored folder appears, stop and ask for help before committing.

In Source Control, enter `Build reusable interest cards with React` as the commit message and select **Commit**. Select **Publish Branch** to send `react-profile` to GitHub. If the branch is already published, choose **Push** from the **...** menu instead.

Use the GitHub Pull Requests view in VS Code to create a pull request into `main`. In the description, say what you built and what you checked.

## Common problems


| What you see                                         | What to check                                                                                                          |
| ---------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------- |
| `node` or `npm` is not found                         | Install the current Node.js LTS release, then completely close and reopen VS Code.                                     |
| Windows says scripts are disabled when you run `npm` | In VS Code, choose **Terminal > Select Default Profile > Command Prompt**, open a new terminal, and try again.         |
| `npm` cannot find `package.json`                     | Run `cd react-page` before `npm run dev` or `npm run build`.                                                           |
| The browser is blank or shows the wrong page         | Use the exact local address printed by the current `npm run dev` command. Do not open `index.html` directly.           |
| A card heading appears without its description       | Compare the prop names in `App.jsx` and `InterestCard.jsx`.                                                            |
| The browser shows a JSX error                        | Start at the named file and line. Match each opening tag, brace, quote, and parenthesis with its closing one.          |
| The local address does not use port 5173             | Use the address printed by the development server. It selects another port when 5173 is busy.                          |
| Git shows thousands of files                         | Stop before committing. Check that `react-page/.gitignore` exists and that `node_modules` and `dist` are listed in it. |
| The branch name already exists                       | Run `git switch react-profile` instead of creating it again.                                                           |
| A push asks for a GitHub username or password        | Run `gh auth status` and `gh auth setup-git`, then try the push again.                                                 |




## What's next

Next week, we will put the card information into an array and use it to make a list. We will use state again to make a search field respond as someone types. After that, we will practice loading API data, using a cart, and following checkout before starting the shared merch project in Week 9.

The complete `App.jsx`, `InterestCard.jsx`, and setup files are on this page. Use them to compare a file that is not working.


## Resources

Everything needed for today's code and explanations is above. These are extra examples or references to return to after the exercise.

- [MDN: Document Object Model](https://developer.mozilla.org/en-US/docs/Web/API/Document_Object_Model) explains the browser objects behind the page.
- [React: Your first component](https://react.dev/learn/your-first-component) gives more component examples.
- [React: Writing markup with JSX](https://react.dev/learn/writing-markup-with-jsx) covers JSX syntax.
- [React: Passing props to a component](https://react.dev/learn/passing-props-to-a-component) explains inputs and destructuring.
- [React: Responding to events](https://react.dev/learn/responding-to-events) gives more handler examples.
- [React: State, a component's memory](https://react.dev/learn/state-a-components-memory) explains remembered values and setters.
- [React: Render and commit](https://react.dev/learn/render-and-commit) gives another page-update trace.
- [React: Preserving and resetting state](https://react.dev/learn/preserving-and-resetting-state) explains component identity.
- [MDN: CSS Grid](https://developer.mozilla.org/en-US/docs/Web/CSS/CSS_grid_layout) gives more layout examples.
- [MDN: Using media queries](https://developer.mozilla.org/en-US/docs/Web/CSS/CSS_media_queries/Using_media_queries) explains responsive conditions.
- [Vite: Getting started](https://vite.dev/guide/) documents the development and build tools.

# Week 5

Last week, we made one React component and used it twice by hand. We still wrote each `<InterestCard />` separately in `App.jsx`. This week, we'll put our interests in a list and have React make those same cards from that list.

We'll also add a search field. Last week, state remembered a title for a click. This week, state remembers search text for typing. A merch page will need the same ideas to show a list of products, remember a selected size, and respond to changes in a cart.

By the end of the meeting, your page should display cards from an array and remember the text you type into an input. We'll finish by using that text to filter the cards. If you need more time, finish the filtering before next week; keep the working list and input first.

## Getting started

The complete practice files are included at the end of this lesson.

Open the whole `practice-page` repository in VS Code. Save and commit any finished Week 4 work before starting this lesson. From a terminal at the repository's top level, run:

```sh
git status
git switch -c interests-state
cd react-page
npm run dev
```

The branch starts from your current saved Week 4 work. If `git status` shows unfinished changes you do not recognize, ask for help before switching branches. Open the exact local address printed by the development server.

We'll keep using the same React project. You can compare your work with the complete practice files below. The reference files go in `react-page/src`. Copy the supplied `App.css` into `src` before continuing. It adds spacing and visible keyboard focus for the input and works alongside the existing `styles.css`. Keep last week's `InterestCard.jsx` — we will drive it from the array.

## Objects and arrays

An object groups information about one thing under property names. Last week, the `props` object held a card's title and description. We can make our own object too:

```js
const interest = {
  id: "games",
  title: "Video games",
  description: "I like learning how games are designed."
};
```

The outer braces hold the object. Each property has a name, a colon, and a value. Commas separate the properties. `interest.title` reads the value under `title`, which is `"Video games"`.

The `id` is an identifier: a value that distinguishes this item from the others. We choose it once and keep it the same even if we change the title.

An array is an ordered list. Create `src/interests.js` and add:

```js
export const interests = [
  {
    id: "games",
    title: "Video games",
    description: "I like learning how games are designed."
  },
  {
    id: "photos",
    title: "Photography",
    description: "I like taking pictures around Hoboken."
  }
];
```

The square brackets, `[` and `]`, hold the array. Each item here is an object, and a comma separates the two objects. `interests[0]` gets the first item; array positions start at zero. `interests[0].title` gets that item's title.

`export` lets another file import this value. This is a named export, so we will use the same name inside braces when importing it.

Save `interests.js`. You should have two objects inside one array. The two-item array above keeps the walkthrough short. The supplied reference adds a Cooking interest. Its objects have the same fields. Searching for `games` still keeps only Video games.

## A function that receives and returns a value

A function can receive information when we call it. In this function, `interest` is the parameter: the name used for the input inside the function.

Last week we wrote two `<InterestCard />`s by hand. This week one function returns that same component for whichever object we give it:

```jsx
function renderInterest(interest) {
  return (
    <InterestCard
      key={interest.id}
      title={interest.title}
      description={interest.description}
    />
  );
}
```

If we call `renderInterest(interests[0])`, we give it the first object. That supplied value is called an argument. Inside that call, `interest.title` becomes the card's title prop.

`return` sends a result back to the code that called the function. Here, the result is JSX describing one `InterestCard`. The parentheses let us spread that JSX over several lines. The function does not change the original object.

`InterestCard` still uses an `<h3>` for the title, just like last week. We'll use `key` in the next step. It gives React the item's stable identity when it appears in a list.

## Making the cards from the list

Replace `src/App.jsx` with this small version while we learn the list code. Your earlier profile is still saved in Git. Keep `InterestCard.jsx` in the folder — we import it here.

```jsx
import InterestCard from "./InterestCard.jsx";
import { interests } from "./interests.js";
import "./App.css";

function renderInterest(interest) {
  return (
    <InterestCard
      key={interest.id}
      title={interest.title}
      description={interest.description}
    />
  );
}

export default function App() {
  return (
    <main>
      <h1>Things I like</h1>
      <div className="interest-list">
        {interests.map(renderInterest)}
      </div>
    </main>
  );
}
```

`.map()` is an array method, which means it is a function available on an array. It calls `renderInterest` once for each item and collects the returned cards into a new array. The JSX braces display that result. We pass `renderInterest` without parentheses so `.map()` can call it with each item.

`key={interest.id}` helps React match a rendered card to its data when the list changes. Each item in this list needs a different key. Use the saved ID, not a newly generated random value or the item's current position. Put `key` on the `InterestCard` in the list, not inside the component file.

Save both files. You should see two cards that look like last week's.

Now add a third object to `interests.js` with a different ID, title, and description. Leave `App.jsx` alone. Save and check that a third card appears. Tell the person next to you how one function produced three different cards.

| Job | Last week | This week |
| --- | --- | --- |
| Show two cards | Write two `<InterestCard />`s by hand. | `.map` over the `interests` array. |
| Change a title | Edit the prop in JSX. | Change it in the array (or later, filter which objects show). |
| Remember a value | Click sets title state. | Typing sets query state. |

## Remembering what someone types

Last week, `useState` remembered a title so a click could change a card. This week it remembers search text so typing can change what we show. Same two jobs: React remembers the value between renders, and the setter requests an update.

A render is React calling a component to work out what the page should show. When we update state, React renders the component again using the new value.

Why not write `let query = ""` inside `App`? Each call to `App` would run that declaration again and start with an empty string. Assigning a different string in a handler also would not tell React to call `App` again. State still provides both pieces.

Add this import at the top of `App.jsx`:

```jsx
import { useState } from "react";
```

Call `useState` at the top of `App`, before its `return` — same top-level rule as last week:

```jsx
const [query, setQuery] = useState("");
```

`useState("")` starts with an empty string. It returns an array containing two things: the current value and a function that updates it. The square-bracket syntax gives those two things names in order. Here, `query` is the search text for this render. `setQuery` asks React to remember a value for the next render.

The empty string is the initial value. React does not reset the search to it every time `App` runs. On later renders of this same component, `useState` gives us the state React has remembered.

Keep this call at the top level of the component. Do not put it inside an event handler or an `if` statement.

Inside `App`, after that state line and before `return`, add:

```jsx
function handleSearch(event) {
  setQuery(event.target.value);
}
```

React passes information about the input event to `handleSearch`. `event.target` is the input that changed, and its `value` is the text currently in it. We give that text to `setQuery`.

Below the heading in the JSX, add:

```jsx
<label htmlFor="interest-search">Search interests</label>
<input
  id="interest-search"
  type="search"
  value={query}
  onChange={handleSearch}
/>
<p>You typed: {query}</p>
```

The label stays visible and tells someone what the field is for. JSX uses `htmlFor` to connect it to the input's matching `id`. `type="search"` describes the kind of text field.

`value={query}` makes React state control the field's displayed value. `onChange={handleSearch}` updates that state when someone types. Together these make a controlled input.

`onChange={handleSearch}` passes the function for React to call when the input changes. Defining that function inside `App` does not run its body during rendering. Writing `onChange={handleSearch()}` would call it immediately while calculating the JSX, before there is an input event to handle.

Save and type. The sentence below the field should repeat the text immediately. Clearing the field should clear that text too. Use `setQuery(...)` to update the state; assigning to `query` directly does not ask React to update the page.

## Follow one page update

Start with the empty search and type `g`. Follow the value through the code we just wrote:


![Typing g calls handleSearch and setQuery. React renders App, compares the result with the last one, commits the You typed paragraph text, and the browser paints it. The same input keeps focus.](https://wiki.sitblueprint.com/uploads/images/gallery/2026-10/react-type-update.png)

1. The browser changes the input's text. React calls `handleSearch` for that change, and `event.target.value` contains `"g"`.
2. The handler calls `setQuery("g")`. This requests new state; it does not edit the paragraph itself.
3. React calls `App` again. `useState` now supplies `"g"` as `query`. The JSX describes the input with that value and a paragraph saying "You typed: g".
4. React commits the needed DOM changes. The paragraph's text changes. The same input element stays on the page with keyboard focus, so you can keep typing.
5. The browser paints the result. The document has stayed open throughout. We have not navigated to a new page or reloaded the HTML file.

The cards have not changed yet because this version still reads the same list. A render can update one part of the page and leave another alone.

## Which value does the handler read?

Let's say the search starts empty and you type `g`. The input now contains `g`, so the event gives us that new text. But what does `query` contain while the handler runs?

Temporarily replace `handleSearch` with this version and open the browser's Console:

```jsx
function handleSearch(event) {
  const nextQuery = event.target.value;
  setQuery(nextQuery);
  console.log("This render's query:", query);
  console.log("The input's new text:", nextQuery);
}
```

Start with an empty field and type `g` once. The first log shows the empty string and the second shows `g`. `setQuery` requested another render; it did not rewrite `query` inside this handler. React calls `App` again with the new state, and that render's `query` is `g`. Each render gets its own values, which is why a `const` declaration can give `query` different text on the next render.

Remove the two `console.log` lines after checking them. Keep `nextQuery` and `setQuery(nextQuery)` as your handler. The supplied reference uses that version.

## Showing matching interests

We can use the search text to choose which objects become cards. This is the next part of the same exercise, so keep the working input before making this change.

Add this inside `App`, below `handleSearch` and above `return`:

```jsx
function matchesSearch(interest) {
  return interest.title.toLowerCase().includes(query.toLowerCase());
}

const filteredInterests = interests.filter(matchesSearch);
```

`.toLowerCase()` returns a lowercase version of a string. `.includes(...)` checks whether a string contains the supplied text and returns `true` or `false`. These are Boolean values: yes or no answers. Comparing lowercase versions lets `games` and `GAMES` find the same title.

`.filter()` calls `matchesSearch` for each interest. It returns a new array containing the items whose answer was `true`. It keeps the original array intact. An empty query matches every title.

In the JSX, replace `interests.map(renderInterest)` with:

```jsx
{filteredInterests.map(renderInterest)}
```

Now `filter` chooses the objects, then `map` makes their cards. We calculate `filteredInterests` from the current `query` each time React renders `App`. It does not need separate state.

Save. Try `games`, `GAMES`, and a word that is in none of the titles. When `query` reaches `"games"`, that render keeps the Video games object and leaves out titles that do not match. The JSX describes the remaining cards, and the commit removes the other cards from the DOM. The existing Video games card can stay because its type and key still match.

When nothing matches, an empty page is not much help. Below the list, add:

```jsx
{filteredInterests.length === 0 && (
  <p>No interests match. Clear the search to see them all.</p>
)}
```

`.length` is the number of items in the array. `===` compares values; here it asks whether that count is exactly zero. `&&` means “and.” In this JSX expression, the paragraph appears only when the comparison is true. This is conditional rendering: choosing what to display based on a condition.


![With query games, filter keeps the Video games object and leaves out Photography. map turns that object into an InterestCard with key games. The original interests array still contains both objects.](https://wiki.sitblueprint.com/uploads/images/gallery/2026-10/search-filter-map.png)

With `query` set to `"games"`, the filter keeps the Video games object. The map then describes one card. Clearing the input lets both objects pass the filter again; neither object was deleted.

Save and check: a matching search shrinks the list, a missing word shows the no-match message, and clearing the field restores every card.

## When something goes wrong

| What you see | What to check |
| --- | --- |
| Only one card appears after adding an object | Confirm the new object is inside the array's square brackets and separated from the previous object by a comma. |
| `.map is not a function` | Check that `interests` is the array, not one object such as `interests[0]`. |
| The list is blank with no syntax error | Make sure `renderInterest` returns its JSX. A function with no `return` does not give `.map()` a card. |
| React warns about keys | Give each object its own ID and keep `key={interest.id}` on the `InterestCard` in the list. |
| The input will not change | Check that `onChange` names `handleSearch` and that the handler passes the input's new text to `setQuery`. |
| React reports too many renders | Pass `handleSearch` to the event prop. Do not call a state setter while rendering the JSX. |
| Search always finds nothing | Compare the property names, then clear the query and try a title that appears in your data. |

## What's next

Next week, the interest data will come from an HTTP response instead of a local import. Keep today's working list and search so you can compare imported data with data the browser loads.

The complete practice files are on this page. Use them to compare a file that is not working.


## Resources

Everything needed for today's code and explanations is above. These are extra examples or references to return to after the exercise.

- [MDN: JavaScript object basics](https://developer.mozilla.org/en-US/docs/Learn_web_development/Core/Scripting/Object_basics)
- [MDN: Arrays](https://developer.mozilla.org/en-US/docs/Learn_web_development/Core/Scripting/Arrays)
- [MDN: Functions](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Functions)
- [MDN: Array.map](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map)
- [MDN: Array.filter](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/filter)
- [React: Rendering Lists](https://react.dev/learn/rendering-lists)
- [React: State, a component's memory](https://react.dev/learn/state-a-components-memory)
- [React: Controlling an input with state](https://react.dev/reference/react-dom/components/input#controlling-an-input-with-a-state-variable)
- [React: Responding to events](https://react.dev/learn/responding-to-events)
- [React: Conditional Rendering](https://react.dev/learn/conditional-rendering)

## Complete practice files

Copy these files into the paths shown below. They are the same files used by the lesson. Keep the filenames and imports together. Keep last week's `InterestCard.jsx` (or copy the version below if you need it).

### `src/InterestCard.jsx`

```jsx
export default function InterestCard(props) {
  return (
    <article className="interest-card">
      <h3>{props.title}</h3>
      <p>{props.description}</p>
    </article>
  );
}
```

### `src/App.jsx`

```jsx
import { useState } from "react";
import InterestCard from "./InterestCard.jsx";
import { interests } from "./interests.js";
import "./App.css";

function renderInterest(interest) {
  return (
    <InterestCard
      key={interest.id}
      title={interest.title}
      description={interest.description}
    />
  );
}

export default function App() {
  const [query, setQuery] = useState("");

  function handleSearch(event) {
    const nextQuery = event.target.value;
    setQuery(nextQuery);
  }

  function handleClear() {
    setQuery("");
  }

  function matchesSearch(interest) {
    return interest.title.toLowerCase().includes(query.toLowerCase());
  }

  const filteredInterests = interests.filter(matchesSearch);

  return (
    <main>
      <h1>Things I like</h1>
      <p>This page reads each interest from an array.</p>

      <label htmlFor="interest-search">Search interests</label>
      <input
        id="interest-search"
        type="search"
        value={query}
        onChange={handleSearch}
        placeholder="Try photography"
      />
      <button type="button" onClick={handleClear}>
        Clear search
      </button>

      <p role="status">Interests shown: {filteredInterests.length}</p>
      <div className="interest-list">
        {filteredInterests.map(renderInterest)}
      </div>
      {filteredInterests.length === 0 && (
        <p>No interests match. Clear the search to see them all.</p>
      )}
    </main>
  );
}
```

### `src/interests.js`

```js
export const interests = [
  {
    id: "games",
    title: "Video games",
    description: "I like learning how games are designed.",
  },
  {
    id: "photos",
    title: "Photography",
    description: "I like taking pictures around Hoboken.",
  },
  {
    id: "cooking",
    title: "Cooking",
    description: "I like trying a new recipe each week.",
  },
];
```

### `src/App.css`

```css
.interest-card h3 {
  font-size: 1.15rem;
  margin: 0;
}

label {
  display: block;
  font-weight: 600;
  margin-bottom: 8px;
}

input {
  width: 100%;
  font: inherit;
  color: inherit;
  padding: 12px;
  border: 1px solid #64748b;
  border-radius: 8px;
}

input:focus-visible {
  outline: 3px solid #1d4ed8;
  outline-offset: 3px;
}

button {
  margin-top: 12px;
  font: inherit;
  padding: 8px 14px;
  border: 1px solid #64748b;
  border-radius: 8px;
  background: #f8fafc;
  cursor: pointer;
}

button:focus-visible {
  outline: 3px solid #1d4ed8;
  outline-offset: 3px;
}
```

# Week 6

Last week, our interests lived in a JavaScript file we imported. A merch site can't work like that. It has to ask another service for the current products, and later tell it what goes in the cart. That's what REST APIs are for. By the end, your page will load its cards with a real GET request, handle an empty list and a failure, and you'll know how to read Fourthwall's API docs, the API our merch site will use. We'll request a small JSON file from our own dev server, so nobody needs a shop account or a token.

## Getting started

The complete practice files are included at the end of this lesson.

Save and commit your Week 5 work. Open a terminal at the top of `practice-page` and create a branch from that saved work:

```sh
git status
git switch -c load-interests
```

Copy the supplied Week 6 `App.jsx` and `App.css` into `react-page/src`. Copy `interests.json` into `react-page/public`. Keep the existing `main.jsx`, `styles.css` and last week's `InterestCard.jsx`. The new `App.jsx` still uses `InterestCard` for each card.

This reference includes a finished request function. For the exercise, find `async function loadInterests()` in your copy of `App.jsx`. Replace that entire function with this empty one, leaving the rest of `App` in place:

```js
function loadInterests() {
}
```

Start the server from `react-page`:

```sh
cd react-page
npm run dev
```

Open the address printed by the terminal. The page should show **Load interests** and a message asking you to click. The button won't do anything until we write its function. If `npm` isn't found, check the Setup page.

## What an API is

The frontend is what runs in the browser: the page, the buttons, and our React code. A server is a program that gets requests and sends back responses. Our Vite dev server is one. A shop's backend is another.

An API (application programming interface) is the set of requests a server agrees to answer. Its docs tell you what you can send and what you'll get back. You never see the server's code or database, just the requests it accepts.

HTTP is the set of rules browsers and servers use to talk. Every exchange is one **request** from the client and one **response** from the server.

## What REST means

REST is a common style for web APIs. It's not something you install. It's a set of habits that make APIs predictable:

1. The API is organized around **resources**, the things it has data about.
2. Each resource has its own **URL**.
3. The **HTTP method** says what you want to do with that resource.
4. The **status code** says how it went.
5. Each request carries everything the server needs to answer it.

Once you know these, most API docs start to look familiar.

## Resources and endpoints

A resource is a noun: a product, a collection, a cart. A REST API gives each one an address. For a shop it might look like this:

| URL path | Resource |
| --- | --- |
| `/products` | All products |
| `/products/blueprint-shirt` | One product, picked out by its slug |
| `/carts/abc123` | One cart, picked out by its ID |

Paths are nouns, not verbs. You won't usually see `/getProducts`. The verb comes from the method.

An **endpoint** is one method plus one path, like `GET /products`. API docs are mostly a list of endpoints.

Query parameters come after `?`, separated by `&`, like `?page=0&size=50`. They tweak the request, like which page of results you want. They don't change which resource you're asking about.

In our exercise, the resource is the class interest list, and its URL is `/interests.json`.

## HTTP methods

The method is the action. These five come up most:

| Method | What it asks for | Shop example | Example path |
| --- | --- | --- | --- |
| `GET` | Read a resource. Changes nothing. | Get the product list. | `/products` |
| `POST` | Create something new, or run an action. | Create a new cart. | `/carts` |
| `PUT` | Replace a whole resource with the one you send. | Replace a saved address. | `/addresses/{addressId}` |
| `PATCH` | Change only some fields of a resource. | Change just the quantity of one item. | `/carts/{cartId}/items/{itemId}` |
| `DELETE` | Remove a resource. | Remove one item from a cart. | `/carts/{cartId}/items/{itemId}` |

These paths show a typical shop API, not a real one. Check the real docs before using any path.

`GET` is safe to repeat. Asking for the product list twice changes nothing. `POST` usually isn't. Send the same "add to cart" twice and you might get two shirts, so watch out for double clicks.

These are the usual meanings, but the docs have the final say. Some APIs use `POST` where others use `PATCH` or `DELETE`. Fourthwall does this, as we'll see below.

Today we only send `GET`, since our JSON file is just a file and can't store anything. We'll send real `POST` requests when we hook up Fourthwall.


## Status codes

Every response starts with a three-digit status code. The first digit tells you the group:

| Group | Meaning | Codes you'll see |
| --- | --- | --- |
| `2xx` | It worked. | `200 OK`, `201 Created`, `204 No Content` |
| `4xx` | Something is wrong with the request. Check what you sent. | `400 Bad Request`, `401 Unauthorized`, `403 Forbidden`, `404 Not Found`, `409 Conflict`, `429 Too Many Requests` |
| `5xx` | The server had a problem. Your request might be fine. | `500 Internal Server Error`, `503 Service Unavailable` |

Quick rule: 4xx means check your code. 5xx means it's the server, so wait and retry.


## Request and response bodies

The body is the data a message carries. A `GET` usually has none, since the URL already says what we want. The response body holds what we asked for.

`POST`, `PUT`, and `PATCH` requests usually have a body saying what to create or change. Most REST APIs use JSON both ways.

### Reading JSON

Open `public/interests.json`. The start should look familiar:

```json
[
  {
    "id": "games",
    "title": "Video games",
    "description": "I like learning how games are designed."
  }
]
```

JSON (JavaScript Object Notation) is a text format for sending data. It's the same array of objects as last week's `interests.js`, minus the `export`. Names and strings need double quotes, and JSON doesn't allow comments or a trailing comma.

Open `/interests.json` at your app's address, like `http://localhost:5173/interests.json`. Your browser just sent a `GET` for that resource and is showing you the response body. Note `public` isn't part of the URL.

That text still has to become JavaScript data before React can use it. That's what `response.json()` does.

## Headers and statelessness

Headers are extra info about a message, separate from the body. A few common ones:

| Header | What it says |
| --- | --- |
| `Content-Type: application/json` | The body is JSON. Sent on responses, and on requests that have a JSON body. |
| `Accept: application/json` | The client would like JSON back. |
| `Authorization` | Proof of who is asking, such as a token. Not every API uses this header. Some put the token in the URL instead. |

REST APIs are **stateless**. The server doesn't remember your earlier requests, so each one has to carry everything: method, URL, any token, any body. That's why a cart API wants the cart ID on every cart request. You tell it which cart, every time.

This is about the server. It's not the same as React state, which is the page remembering values between renders.

![A request has a method (GET), a URL for the resource (/interests.json), headers such as Accept: application/json, and no body for GET. The response has a status code (200 OK), headers such as Content-Type: application/json, and a JSON body with the interests array. Each request carries everything the server needs because the server does not remember earlier requests.](https://wiki.sitblueprint.com/uploads/images/gallery/2026-11/rest-anatomy.png)

## Making a GET request from React

Now let's use all that. Our page will send `GET /interests.json`, check the status code, and read the JSON body.

### State for a request

Look near the start of `App`. The reference declares three state values:

```jsx
const [interests, setInterests] = useState([]);
const [status, setStatus] = useState("idle");
const [error, setError] = useState("");
```

`interests` starts empty. `status` starts as `"idle"`, meaning we haven't asked yet. `error` holds a message if loading fails.

The page uses four status words:

| Page status | What someone should see |
| --- | --- |
| `idle` | A button and instructions to load the list. |
| `loading` | A loading message while the request is unfinished. |
| `success` | Cards, or an explanation that the returned list is empty. |
| `error` | An error message and a way to try again. |

These are our own React state, not the server's HTTP status code.

![The page starts idle. Clicking Load interests changes it to loading. A readable list with the right fields changes it to success, which shows cards or says the list is empty. A failed request, an HTTP error, unreadable JSON or wrong fields change it to error. Another click from success or error starts loading again.](https://wiki.sitblueprint.com/uploads/images/gallery/2026-11/request-states.png)

An empty array is still `success`. The request worked, there's just nothing to show. `error` means we never got a usable list.

### Waiting for a response

`fetch()` starts a request and gives back a Promise, a value for work that finishes later. An `async` function lets us use `await`, which pauses that function (not the whole browser) until the work is done.

These two lines get and read our response:

```js
const response = await fetch("/interests.json");
const data = await response.json();
```

`fetch` sends a `GET` unless you tell it otherwise. The first line gives a Response with the status, headers, and body. The second reads the body as JSON. Getting a response and reading it are two separate steps.

We also have to check the status. `fetch` still hands back a Response for a `404` or `500`. It only fails outright when nothing comes back, like when you're offline. `response.ok` is true for 200 to 299, so `!response.ok` catches the 4xx and 5xx groups.

### Handling failures

A few new bits of JavaScript first:

- `if (x) { ... }` runs the braces only when `x` is true.
- `!` means "not", so `!response.ok` means the response failed.
- `throw new Error("...")` makes an error and jumps out.
- `try` wraps code that might fail. If it does, `catch (failure)` runs instead.
- `failure.message` is the error's text. `+` joins strings.
- `return;` just ends the function.

`isInterest` (already in the file) checks one object's fields. `Array.isArray(data)` checks we got a list, and `.every(isInterest)` checks every item. `||` means "or", so if either check fails we reject it.

Replace the empty `loadInterests` function with:

```jsx
async function loadInterests() {
  if (status === "loading") {
    return;
  }

  setStatus("loading");
  setError("");

  try {
    const response = await fetch("/interests.json");

    if (!response.ok) {
      throw new Error("The request failed with status " + response.status + ".");
    }

    const data = await response.json();

    if (!Array.isArray(data) || !data.every(isInterest)) {
      throw new Error("The response does not contain the interest fields we need.");
    }

    setInterests(data);
    setStatus("success");
  } catch (failure) {
    setError("Could not load interests. " + failure.message);
    setStatus("error");
  }
}
```

If a request is already running, we stop. Otherwise we show loading and clear any old error. A good response with the right fields gets saved and we show success. A failed request, bad JSON, or wrong fields all land in `catch`.

Save and click **Load interests**. The cards should appear.

This is the same update as Week 5's search. The setters ask React to render again, only now the value came from a response instead of a text field. If we never called a setter, nothing on screen would change.

#### Checking the response's shape

Look at the supplied check near the top of `App.jsx`:

```js
function isInterest(value) {
  return (
    value !== null &&
    typeof value === "object" &&
    typeof value.id === "string" &&
    typeof value.title === "string" &&
    typeof value.description === "string"
  );
}
```

It wants an object with three string fields. `typeof` gives a value's type, and `&&` means every check has to pass. (We check for `null` separately because JavaScript says `typeof null` is `"object"`.) This lets us show a clear error instead of crashing. Products will need their own check.

### Showing what is happening

The supplied button connects to our function and is disabled while loading:

```jsx
<button type="button" onClick={loadInterests} disabled={status === "loading"}>
  Load interests
</button>
```

Like `onChange` last week, we pass the function without calling it. While loading, `disabled` is true, so nobody can click twice.

The page picks its message with conditions, like week 5's no-match message:

```jsx
{status === "success" && interests.length === 0 && (
  <p>No interests were returned.</p>
)}
```

This shows when loading worked but the list is empty. That's not a failure. In the full file, `role="status"` lets a screen reader announce changes and `role="alert"` announces errors.

## Inspecting the request

Open **Inspect**, then **Network**. Click **Load interests** again and find the `interests.json` request.

Match it to the REST terms from earlier:

1. In **Headers**, find the request URL, the method, and the status code. The URL is the resource. The method should be `GET` and the status should be `200`.
2. Still in **Headers**, scroll to the response headers and find `Content-Type`. It should say the body is JSON.
3. In **Response** or **Preview**, find the response body: the returned array and its objects. This is the data our function passed to `setInterests`.
4. Compare a returned title with its card on the page.

If it loads too fast to see, turn on throttling in the Network panel and click again. You should see the loading message and a disabled button. Turn throttling off after. Nothing loads until you click, since the click handler starts the request.

## Try an empty list and a failure

Save a copy of the working JSON. Then replace it with:

```json
[]
```

Save and click the button. You should get **No interests were returned**. Restore the data.

Next, change `"title"` to `"heading"` in one object. It's still valid JSON, just the wrong shape. Load it, read the error, fix the name, and retry without refreshing.

Then pick **Offline** in the Network panel and click. You should get the error. Switch back to normal after.

Last, change the URL in `loadInterests` to `"/missing.json"` and click. Check the row in Network. Vite sometimes answers missing paths with its own HTML page and a `200`, so you might get a JSON error instead of a `404`. Either way the page shows an error, which is why we check both the status and the shape. Put the URL back.

## Reading API docs: Fourthwall

Our merch site will use Fourthwall's Storefront API. Its docs follow the same REST habits, so let's read them like any new API. No token needed, we're just reading.

Here are the endpoints the project will use:

| Endpoint | What it does |
| --- | --- |
| `GET /v1/collections/all/products` | Read the products in the `all` collection |
| `GET /v1/products/{slug}` | Read one product by its slug |
| `POST /v1/carts` | Create a new cart |
| `GET /v1/carts/{cartId}` | Read one cart |
| `POST /v1/carts/{cartId}/add` | Add items to a cart |
| `POST /v1/carts/{cartId}/change` | Change item quantities |
| `POST /v1/carts/{cartId}/remove` | Remove items |

These come from Fourthwall's [Storefront API schema](https://docs.fourthwall.com/openapi/storefront.json), checked November 2, 2026. Each one has its own reference page, for example [Get Product](https://docs.fourthwall.com/api-reference/storefront/products/get-product), [Create Cart](https://docs.fourthwall.com/api-reference/storefront/carts/create-cart), [Get Cart](https://docs.fourthwall.com/api-reference/storefront/carts/get-cart), and [Add to Cart](https://docs.fourthwall.com/api-reference/storefront/carts/add-to-cart).

`{slug}` and `{cartId}` are placeholders for real values. Every path starts from `https://storefront-api.fourthwall.com`.

Look at the methods. Reading is `GET`, but every cart change is `POST` with an action word at the end. Another API might use `PATCH` or `DELETE` here. That's why you read the docs instead of guessing.

A full product-list request looks like this:

```text
GET https://storefront-api.fourthwall.com/v1/collections/all/products?storefront_token=YOUR_TOKEN&currency=USD&page=0&size=50
```

This isn't a command to run, just a request to read. `YOUR_TOKEN` stands for the shop's Storefront token, and since the API is stateless, it goes on every request. Fourthwall puts it in a `storefront_token` query parameter rather than an `Authorization` header ([Storefront getting started](https://docs.fourthwall.com/storefront/getting-started)). `currency` picks the price currency, and `page` and `size` pick which slice of products comes back.

The response body, described in [Fetching Products](https://docs.fourthwall.com/storefront/products), is an object containing `results` and `paging`, not a bare array. `results` holds the products. `paging` describes the page you got: `pageNumber`, `pageSize`, `elementsSize`, `elementsTotal`, `totalPages`, and `hasNextPage`. This shortened example uses made-up values and skips most product fields:

```json
{
  "results": [
    {
      "type": "PRODUCT",
      "id": "example-product",
      "name": "Blueprint shirt",
      "slug": "blueprint-shirt",
      "variants": []
    }
  ],
  "paging": {
    "hasNextPage": false
  }
}
```

So the products are at `data.results`, and the first name is `data.results[0].name`. Our interests use `title`, Fourthwall uses `name`. Each variant has an ID and a `unitPrice`, which we'll need for the cart.

The docs list errors too. A slug that doesn't exist on `GET /v1/products/{slug}` returns `404` with a body whose `code` is `OFFER_SLUG_NOT_FOUND_ERROR`. Good APIs tell you what went wrong, not just the number.

So just swapping the URL in our exercise wouldn't work. We'd need a check for product fields, handle more pages, and watch `type`, since bundles come back too.

Open Fourthwall's Get Product page (under Resources) and write down these five things. It works for any API:

1. The method and path.
2. The required parameters, and where each goes (path, query, or body).
3. The fields in a successful response.
4. The error status codes it can return.
5. How it expects you to prove access, such as a token.

One more thing: Fourthwall is a different site from ours, so the browser only lets us read its responses because Fourthwall allows it (this rule is called CORS). Not every API does, and `mode: "no-cors"` won't fix it.

## When something goes wrong

| What you see | What to check |
| --- | --- |
| No request in Network | Confirm the button uses `onClick={loadInterests}` and the function contains `fetch`. |
| JSON parsing error or an HTML response | Open the exact request URL. Confirm the file is `public/interests.json`, not `src/interests.json` or `public/public/interests.json`. |
| Wrong-field error | Check `id`, `title`, and `description` and confirm that the outer value is an array. |
| The page stays in loading | Check the Console, keep both success and catch status updates, and make sure you restored normal network settings. |
| HTTP `401` or `403` on a future API call | Read the response and check the service's access instructions and configured token. |
| HTTP `404` | Check the endpoint and resource ID. A missing local path may instead return Vite's HTML page, which causes a JSON parsing error. |
| HTTP `429` | Too many requests were made. Follow the API's retry guidance instead of repeatedly clicking. |
| HTTP `500` | The server reported an error. Keep the error message and retry path useful; changing the page's CSS will not fix the server. |

The meanings of other HTTP codes are listed on the MDN status codes page under Resources.

## What's next

Before next week, restore the JSON and the URL, and turn off throttling and Offline. Add one interest to the JSON, load it, and check its card shows up. Commit with a message such as `Load interests with a GET request` and push the branch. If GitHub asks you to sign in, use the GitHub CLI steps on the Setup page.

Next week, we'll use state to pick a product variant and update a small practice cart. Later, those cart changes become the `POST` requests above.

## Resources

Everything needed for today's code and explanations is above. These are extra examples or references to return to after the exercise.

- [MDN: Overview of HTTP](https://developer.mozilla.org/en-US/docs/Web/HTTP/Guides/Overview)
- [MDN: Working with JSON](https://developer.mozilla.org/en-US/docs/Learn_web_development/Core/Scripting/JSON)
- [MDN: Using Fetch](https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch)
- [MDN: async functions](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/async_function)
- [MDN: try...catch](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/try...catch)
- [MDN: Response.ok](https://developer.mozilla.org/en-US/docs/Web/API/Response/ok)
- [MDN: typeof](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/typeof)
- [MDN: CORS](https://developer.mozilla.org/en-US/docs/Web/HTTP/Guides/CORS)
- [MDN: HTTP request methods](https://developer.mozilla.org/en-US/docs/Web/HTTP/Reference/Methods)
- [MDN: HTTP headers](https://developer.mozilla.org/en-US/docs/Web/HTTP/Reference/Headers)
- [MDN: HTTP status codes](https://developer.mozilla.org/en-US/docs/Web/HTTP/Reference/Status)
- [Fourthwall: Fetching Products](https://docs.fourthwall.com/storefront/products)
- [Fourthwall: Get Product](https://docs.fourthwall.com/api-reference/storefront/products/get-product)
- [Fourthwall: Storefront getting started](https://docs.fourthwall.com/storefront/getting-started)
- [Fourthwall: Storefront API schema](https://docs.fourthwall.com/openapi/storefront.json)

## Complete practice files

Copy these files into the paths shown below. They are the same files used by the lesson. Keep the filenames and imports together. Keep last week's `InterestCard.jsx` (or copy the version below if you need it).

### `src/InterestCard.jsx`

```jsx
export default function InterestCard(props) {
  return (
    <article className="interest-card">
      <h3>{props.title}</h3>
      <p>{props.description}</p>
    </article>
  );
}
```

### `src/App.jsx`

```jsx
import { useState } from "react";
import InterestCard from "./InterestCard.jsx";
import "./App.css";

function isInterest(value) {
  return (
    value !== null &&
    typeof value === "object" &&
    typeof value.id === "string" &&
    typeof value.title === "string" &&
    typeof value.description === "string"
  );
}

function renderInterest(interest) {
  return (
    <InterestCard
      key={interest.id}
      title={interest.title}
      description={interest.description}
    />
  );
}

export default function App() {
  const [interests, setInterests] = useState([]);
  const [status, setStatus] = useState("idle");
  const [error, setError] = useState("");

  async function loadInterests() {
    if (status === "loading") {
      return;
    }

    setStatus("loading");
    setError("");

    try {
      const response = await fetch("/interests.json");

      if (!response.ok) {
        throw new Error("The request failed with status " + response.status + ".");
      }

      const data = await response.json();

      if (!Array.isArray(data) || !data.every(isInterest)) {
        throw new Error("The response does not contain the interest fields we need.");
      }

      setInterests(data);
      setStatus("success");
    } catch (failure) {
      setError("Could not load interests. " + failure.message);
      setStatus("error");
    }
  }

  return (
    <main>
      <h1>Load my interests</h1>
      <p>
        This practice page requests a JSON file from the same server as the page.
      </p>
      <button type="button" onClick={loadInterests} disabled={status === "loading"}>
        Load interests
      </button>

      <div role="status">
        {status === "idle" && <p>Click the button to request the list.</p>}
        {status === "loading" && <p>Loading interestsâ€¦</p>}
        {status === "success" && interests.length > 0 && (
          <p>Interests loaded: {interests.length}</p>
        )}
        {status === "success" && interests.length === 0 && (
          <p>No interests were returned.</p>
        )}
      </div>

      {status === "error" && (
        <p role="alert">{error} Check the Network tab, then click Load interests to try again.</p>
      )}
      {status === "success" && (
        <div className="interest-list">{interests.map(renderInterest)}</div>
      )}
    </main>
  );
}
```

### `src/App.css`

```css
.interest-card h3 {
  font-size: 1.15rem;
  margin: 0;
}

button:disabled {
  background: #475569;
  cursor: wait;
}

[role="alert"] {
  color: #991b1b;
  border-left: 4px solid #b91c1c;
  padding: 12px;
  background: #fef2f2;
}
```

### `public/interests.json`

```json
[
  {
    "id": "games",
    "title": "Video games",
    "description": "I like learning how games are designed."
  },
  {
    "id": "photos",
    "title": "Photography",
    "description": "I like taking pictures around Hoboken."
  },
  {
    "id": "cooking",
    "title": "Cooking",
    "description": "I like trying a new recipe each week."
  }
]
```

# Week 7

Last week, our page asked a server for a list and showed it. This week we're building the thing every store has: a cart. And we're building it together, one piece at a time. You'll start with a page that just shows a shirt. By the end of the meeting you'll be able to pick a size, add it to a cart, add it again and watch the quantity go up, and remove it. Every one of those is a few lines you typed yourself.

The products and prices are made up, and the cart only lives in React state (so refreshing the page empties it). Adding something doesn't reserve a shirt, place an order, or charge anyone. We'll get to the real store cart later.

## Getting started

Save and commit your Week 6 work. Open a terminal at the top of `<span class="editor-theme-code">practice-page</span>` and make a new branch from it:

```sh
git status
git switch -c cart-practice
```

If Git says that branch already exists, use `<span class="editor-theme-code">git switch cart-practice</span>` instead.

Now we need a starting point. In `<span class="editor-theme-code">react-page/src</span>`, replace `<span class="editor-theme-code">App.jsx</span>` and `<span class="editor-theme-code">App.css</span>` with the starter versions below, and make a new file called `<span class="editor-theme-code">products.js</span>`. Keep `<span class="editor-theme-code">main.jsx</span>` and `<span class="editor-theme-code">styles.css</span>` the way they are. (Your Week 6 work is still saved in Git, so nothing is lost.) The same three files are also in [week-07-starter.zip](https://wiki.sitblueprint.com/attachments/24) if you'd rather download than copy.

### `<span class="editor-theme-code">src/products.js</span>`

```js
// Made-up practice products. Prices are in cents, so 2400 means $24.00.
export const products = [
  {
    id: "demo-shirt",
    name: "Practice T-shirt",
    variants: [
      { id: "demo-shirt-small", label: "Small", priceMinor: 2400, available: true },
      { id: "demo-shirt-medium", label: "Medium", priceMinor: 2400, available: true },
      { id: "demo-shirt-large", label: "Large", priceMinor: 2400, available: false },
    ],
  },
];
```

### `<span class="editor-theme-code">src/App.css</span>`

```css
section + section {
  margin-top: 24px;
}

label {
  display: block;
  font-weight: 600;
  margin: 16px 0 8px;
}

select {
  display: block;
  width: 100%;
  font: inherit;
  color: inherit;
  background: white;
  padding: 12px;
  border: 1px solid #64748b;
  border-radius: 8px;
  margin-bottom: 16px;
}

select:focus-visible {
  outline: 3px solid #1d4ed8;
  outline-offset: 3px;
}

.remove-button {
  color: #1d4ed8;
  background: #eff6ff;
  border: 1px solid #1d4ed8;
}

.cart-subtotal {
  font-size: 1.2rem;
  font-weight: 700;
}

button:disabled {
  background: #475569;
  cursor: not-allowed;
}
```

### `<span class="editor-theme-code">src/App.jsx</span>` (starter)

```javascript
import "./App.css";

const product = products[0];

function formatPrice(priceMinor) {
  return (priceMinor / 100).toLocaleString("en-US", {
    style: "currency",
    currency: "USD",
  });
}

export default function App() {
  return (
    <main>
      <h1>Practice cart</h1>
      <p>Made-up products. This cart lives in React state, so refreshing the page empties it.</p>

      <section className="interest-card" aria-labelledby="product-heading">
        <h2 id="product-heading">{product.name}</h2>
        <p>{formatPrice(product.variants[0].priceMinor)}</p>
        {/* Step 1: the size dropdown goes here */}
      </section>

      <section aria-labelledby="cart-heading">
        <h2 id="cart-heading">Your cart</h2>
        <p>Your cart is empty.</p>
      </section>
    </main>
  );
}
```

Start the server from `<span class="editor-theme-code">react-page</span>`:

```sh
cd react-page
npm run dev
```

Open the address the terminal prints. You should see **Practice cart**, a Practice T-shirt for $24.00, and "Your cart is empty." That's it for now. There's no dropdown and no button yet, because that's what we're about to write. If `<span class="editor-theme-code">npm</span>` isn't found, check the Setup page.

Leave the dev server running the whole time. Every time you save, the page updates by itself.

## What a cart has to know

A product list and a cart sound like the same thing, but they do pretty different jobs. The product list describes what you *can* buy. The cart describes what *this person* picked and how many.

Open `<span class="editor-theme-code">products.js</span>`. There's one product, the Practice T-shirt, and it has three **variants**. A variant is one specific option of a product that you can actually buy, like the Small T-shirt. All three sizes belong to `<span class="editor-theme-code">demo-shirt</span>`, but each one has its own variant ID.

That's the big idea for today: the cart needs to remember the variant, not just the product. If we only saved `<span class="editor-theme-code">demo-shirt</span>`, a Small and a Medium would look like the same thing, and someone ordering one of each would get two of whatever we guessed.

`<span class="editor-theme-code">available</span>` is a Boolean (`<span class="editor-theme-code">true</span>` or `<span class="editor-theme-code">false</span>`). Large is `<span class="editor-theme-code">false</span>`, so it'll show up as sold out.

`<span class="editor-theme-code">priceMinor</span>` is the price in cents, so `<span class="editor-theme-code">2400</span>` means $24.00. We store whole cents because decimals in JavaScript can get weird (try `<span class="editor-theme-code">0.1 + 0.2</span>` in the Console sometime). `<span class="editor-theme-code">formatPrice</span>` in the starter turns cents into dollars, and it's the only place we divide by 100. These field names are our practice format, not Fourthwall's. The real API has its own fields, and you always go by its docs.

![The demo-shirt product has three variants. Small, demo-shirt-small, available true. Medium, demo-shirt-medium, available true. Large, demo-shirt-large, available false, so it shows as sold out. Adding Small makes a cart line with variantId demo-shirt-small, label Small, quantity 1 and unitPriceMinor 2400. Adding Small again raises that same line to quantity 2. Adding Medium makes a second, separate line. 2400 means $24.00, and these fields are our practice format, not Fourthwall's.](https://wiki.sitblueprint.com/uploads/images/gallery/2026-11/vjcproduct-variant-cart.png)

Here's what we're building toward. The cart line remembers the variant ID. Adding Small again doesn't make a second line, it just bumps the quantity. Adding Medium does make a second line.

## Step 1: Pick a size

First, the page needs to remember which size is picked. That's state, same as the search box in Week 5.

At the top of `<span class="editor-theme-code">App.jsx</span>`, add the `<span class="editor-theme-code">useState</span>` import above the `<span class="editor-theme-code">products</span>` import, so the imports look like this:

```jsx
import { useState } from "react";
import { products } from "./products.js";
```

Next, inside `<span class="editor-theme-code">App</span>`, right under the `<span class="editor-theme-code">export default function App() {</span>` line, add the state and a function to update it:

```jsx
const [selectedVariantId, setSelectedVariantId] = useState(product.variants[0].id);

  function handleVariantChange(event) {
    setSelectedVariantId(event.target.value);
  }
```

`<span class="editor-theme-code">selectedVariantId</span>` starts as the first variant's ID, so the page starts on Small.

Now find these two lines in the product section:

```jsx
<p>{formatPrice(product.variants[0].priceMinor)}</p>
        {/* Step 1: the size dropdown goes here */}
```

Delete both of them and put this in their place:

```jsx
<label htmlFor="variant">Size</label>
        <select id="variant" value={selectedVariantId} onChange={handleVariantChange}>
          {product.variants.map((variant) => (
            <option key={variant.id} value={variant.id} disabled={!variant.available}>
              {variant.label}, {formatPrice(variant.priceMinor)}
              {!variant.available && " (sold out)"}
            </option>
          ))}
        </select>
        <p>Selected: {selectedVariantId}</p>
```

Save. You should see a Size dropdown with Small, Medium, and Large, and Large should be greyed out with "(sold out)". Change it to Medium, and the "Selected:" line should change to `<span class="editor-theme-code">demo-shirt-medium</span>`.

So what did we just write? This is the same controlled input from Week 5, just a dropdown this time. `<span class="editor-theme-code">value</span>` comes from state, and `<span class="editor-theme-code">handleVariantChange</span>` puts `<span class="editor-theme-code">event.target.value</span>` back into state. We `<span class="editor-theme-code">.map()</span>` over the variants to make one `<span class="editor-theme-code"><option></span>` each, and each one needs a `<span class="editor-theme-code">key</span>`, like our interest cards did.

Each option's `<span class="editor-theme-code">value</span>` is the variant ID, and the text between the tags is the label people read. That way we could rename "Small" to "S" and the cart wouldn't care, because the ID stays the same.

`<span class="editor-theme-code">!</span>` flips a Boolean, so a sold-out variant gives `<span class="editor-theme-code">disabled={true}</span>`. Same idea with `<span class="editor-theme-code">&&</span>` from Week 5: the "(sold out)" text only shows up when the variant isn't available.

The "Selected:" line is just there so we can see the state. We'll delete it in Step 3.

## Step 2: Add to cart

Now we need the cart itself. The cart is a list, so it starts as an empty array. Right under the `<span class="editor-theme-code">const [selectedVariantId, setSelectedVariantId] = useState(...)</span>` line, add:

```jsx
const [cart, setCart] = useState([]);
```

Now the function that runs when someone clicks Add. Put this right after the closing `<span class="editor-theme-code">}</span>` of `<span class="editor-theme-code">handleVariantChange</span>`:

```jsx
function handleAdd(variantId) {
    const variant = product.variants.find((option) => option.id === variantId);

    setCart([
      ...cart,
      {
        variantId: variant.id,
        name: product.name,
        label: variant.label,
        quantity: 1,
        unitPriceMinor: variant.priceMinor,
      },
    ]);
  }
```

Now the button. Right under the `<span class="editor-theme-code"><p>Selected: {selectedVariantId}</p></span>` line, add:

```jsx
<button type="button" onClick={() => handleAdd(selectedVariantId)}>
          Add to cart
        </button>
```

Last piece: we need to actually show the cart. In the cart section, find:

```jsx
<p>Your cart is empty.</p>
```

Replace it with:

```jsx
{cart.length === 0 && <p>Your cart is empty.</p>}
        <div className="interest-list">
          {cart.map((line) => (
            <article className="interest-card" key={line.variantId}>
              <h3>{line.name}, {line.label}</h3>
              <p>{formatPrice(line.unitPriceMinor)} each</p>
              <p>Quantity: {line.quantity}</p>
            </article>
          ))}
        </div>
```

Save. Click **Add to cart** once. You should see one Practice T-shirt, Small, quantity 1.

Now let's look at what we just typed, top to bottom.

`<span class="editor-theme-code">.find()</span>` goes through an array and gives back the first item that passes your test. Here, it's the variant whose ID matches the one we picked.

Then we build the next cart. `<span class="editor-theme-code">...cart</span>` is spread syntax. It copies everything from the old array into a new one, and our new line goes at the end. We make a new array instead of calling `<span class="editor-theme-code">cart.push(...)</span>`, because `<span class="editor-theme-code">push</span>` changes the array React is already holding. React compares the old and new state to decide whether to render again, so if you edit the old array in place, the page might not update.

In the button, the arrow (`<span class="editor-theme-code">() => ...</span>`) matters. It's a tiny function that waits for the click. If you wrote `<span class="editor-theme-code">onClick={handleAdd(selectedVariantId)}</span>`, it would run while React is drawing the page, before anyone clicked. Same mistake as `<span class="editor-theme-code">onChange={handleSearch()}</span>` in Week 5.

The cart list is the same `<span class="editor-theme-code">.map()</span>` as our interest cards. The empty message only shows up when there's nothing in the cart, and each line's `<span class="editor-theme-code">key</span>` is its `<span class="editor-theme-code">variantId</span>`.

Now click it again.

### Two lines?

You should see *two* Small lines, each with quantity 1. Open the browser's Console (right-click, Inspect, Console). React is complaining: "Encountered two children with the same key."

That's the bug we wanted to see. Our `<span class="editor-theme-code">handleAdd</span>` always adds a new line, even when that size is already in the cart. React is mad because we told it `<span class="editor-theme-code">variantId</span>` is what makes each line unique, and now two lines have the same one.

Refresh the page to empty the cart. Now let's fix it.

In `<span class="editor-theme-code">handleAdd</span>`, find this line:

```jsx
const variant = product.variants.find((option) => option.id === variantId);
```

Right under it, add:

```jsx
if (!variant || !variant.available) {
      return;
    }

    const existingLine = cart.find((line) => line.variantId === variantId);
    if (existingLine) {
      setCart(
        cart.map((line) => {
          if (line.variantId === variantId) {
            return { ...line, quantity: line.quantity + 1 };
          }
          return line;
        })
      );
      return;
    }
```

Leave the `<span class="editor-theme-code">setCart([...cart, { ... }])</span>` that was already there, right below what you just pasted. That's still how a brand-new size gets added. Your whole `<span class="editor-theme-code">handleAdd</span>` should now look like this (check your braces against it):

```jsx
function handleAdd(variantId) {
    const variant = product.variants.find((option) => option.id === variantId);
    if (!variant || !variant.available) {
      return;
    }

    const existingLine = cart.find((line) => line.variantId === variantId);
    if (existingLine) {
      setCart(
        cart.map((line) => {
          if (line.variantId === variantId) {
            return { ...line, quantity: line.quantity + 1 };
          }
          return line;
        })
      );
      return;
    }

    setCart([
      ...cart,
      {
        variantId: variant.id,
        name: product.name,
        label: variant.label,
        quantity: 1,
        unitPriceMinor: variant.priceMinor,
      },
    ]);
  }
```

Read it top to bottom:

1. If the variant doesn't exist or isn't available, stop. `<span class="editor-theme-code">return</span>` ends the function early, so nothing gets added.
2. Look for a cart line that already has this variant ID.
3. If there is one, make a new cart where that line's quantity is 1 higher, and stop there.
4. If there isn't, we fall through to the `<span class="editor-theme-code">setCart([...cart, ...])</span>` we already had, which adds a new line.

`<span class="editor-theme-code">.map()</span>` visits every line and returns one result for each. For the line we're bumping, `<span class="editor-theme-code">{ ...line, quantity: line.quantity + 1 }</span>` makes a new object with all the old fields copied in, then replaces `<span class="editor-theme-code">quantity</span>`. Every other line comes back the way it was. In Week 5, `<span class="editor-theme-code">.map()</span>` turned data into cards. Here it turns data into new data. Same method, it just depends on what you return.

Don't write `<span class="editor-theme-code">existingLine.quantity = existingLine.quantity + 1</span>`. That edits an object React is already holding, which is the same problem as `<span class="editor-theme-code">push</span>`.

You might wonder why we check `<span class="editor-theme-code">available</span>` when the dropdown already greys out Large. The disabled option helps the person using the page. The check in the function stops any other code from adding something it shouldn't. (A real store checks again on its server, since anyone can mess with what a browser sends.)

Save, then try it:

1. Clear the Console (the circle-with-a-line icon at its top left) so the old warning is gone. Add Small twice. You should see **one** line with quantity 2, and no new warning.
2. Pick Medium and add it. You should see a second, separate line for Medium.

That's the variant idea working. If Small and Medium ever end up on one line, something is matching on the product ID instead of the variant ID.

## Step 3: Move the button into its own component

Right now the button lives inside `<span class="editor-theme-code">App</span>`. On the merch site, one person might build the product controls and someone else the cart, so let's practice splitting the button out. The catch is that the button needs to change the cart, and the cart lives in `<span class="editor-theme-code">App</span>`.

So far, props have carried text, like a card's title. Props can also carry a function. That's how a child tells its parent that something happened.

Above `<span class="editor-theme-code">export default function App() {</span>` (outside `<span class="editor-theme-code">App</span>`, not inside it), add:

```jsx
function AddButton(props) {
  function handleClick() {
    props.onAdd(props.variantId);
  }

  return (
    <button type="button" onClick={handleClick}>
      Add to cart
    </button>
  );
}
```

Now, back in `<span class="editor-theme-code">App</span>`'s JSX, find the debug line and the button from Step 2. That's everything from `<span class="editor-theme-code"><p>Selected:</span>` down to the button's `<span class="editor-theme-code"></button></span>`:

```jsx
<p>Selected: {selectedVariantId}</p>
        <button type="button" onClick={() => handleAdd(selectedVariantId)}>
          Add to cart
        </button>
```

Delete all of that and replace it with:

```jsx
<AddButton variantId={selectedVariantId} onAdd={handleAdd} />
```

Save. The "Selected:" line is gone, but Add should work exactly like before. Small twice still gives quantity 2, and Medium still gets its own line.

Here's what happens when you click:

![App owns selectedVariantId and cart. It passes the selected ID and its handleAdd function to AddButton as props. A browser click calls the child handleClick, which calls props.onAdd(props.variantId). That runs App handleAdd with demo-shirt-small, which finds the variant and calls setCart with a new array. React renders the updated cart. Passing onAdd={handleAdd} does not call it during rendering.](https://wiki.sitblueprint.com/uploads/images/gallery/2026-11/9Crcallback-to-parent.png)

`<span class="editor-theme-code">App</span>` hands the button two things: the selected ID, and its own `<span class="editor-theme-code">handleAdd</span>` function. When someone clicks, the child calls `<span class="editor-theme-code">props.onAdd(...)</span>`, which is really `<span class="editor-theme-code">App</span>`'s `<span class="editor-theme-code">handleAdd</span>`, and passes it the ID. The button never touches the cart itself.

Why not just give `<span class="editor-theme-code">AddButton</span>` its own cart? Because lots of parts of the page need the same cart. The product controls add to it, the cart list shows it, and later a checkout button reads it. If each one kept its own copy, they'd disagree. So the cart lives in the closest parent that all of them share (here that's `<span class="editor-theme-code">App</span>`), and the children get what they need through props. React's docs call moving state up to that shared parent "lifting state up."

`<span class="editor-theme-code">onAdd</span>` is a name we made up. React doesn't know it means anything. `<span class="editor-theme-code">onClick</span>` on the real `<span class="editor-theme-code"><button></span>` is the built-in one that listens for the browser's click.

Keep it as `<span class="editor-theme-code">onAdd={handleAdd}</span>`, with no parentheses. `<span class="editor-theme-code">onAdd={handleAdd(selectedVariantId)}</span>` would call it right away while React is drawing the page.

## Step 4: Remove an item

Each cart line needs a Remove button, and the button needs to tell us *which* line.

Inside `<span class="editor-theme-code">App</span>`, right above the `<span class="editor-theme-code">return (</span>` that starts the page's JSX (the one with `<span class="editor-theme-code"><main></span>` under it, not the one in `<span class="editor-theme-code">AddButton</span>`), add:

```jsx
function handleRemove(variantId) {
    setCart(cart.filter((line) => line.variantId !== variantId));
  }
```

This is `<span class="editor-theme-code">.filter()</span>` from Week 5. It makes a new array with only the items that pass the test. `<span class="editor-theme-code">!==</span>` means "is not equal to." So read it as "keep every line whose variant ID isn't the one we're removing."

`<span class="editor-theme-code">(line) => line.variantId !== variantId</span>` is an arrow function. `<span class="editor-theme-code">line</span>` is the parameter, and whatever comes after the arrow is what it returns. It does the same job as the named `<span class="editor-theme-code">matchesSearch</span>` function we passed to `<span class="editor-theme-code">.filter()</span>` in Week 5. We just wrote it right inside the call because we only need it there.

Now the button. In the cart list, right under `<span class="editor-theme-code"><p>Quantity: {line.quantity}</p></span>`, add:

```jsx
<button
                type="button"
                className="remove-button"
                onClick={() => handleRemove(line.variantId)}
              >
                Remove
              </button>
```

Each line passes its own `<span class="editor-theme-code">variantId</span>`, so we wrap the call in an arrow again. That arrow waits for the click.

Save. Add Small and Medium, then click Remove on Small. Medium should still be there. Remove Medium too, and you should see "Your cart is empty." again.

## When the cart lives on a server

Our cart runs instantly in the browser. The merch site's cart will be different, because Fourthwall holds it. Remember these from last week?

<table id="bkmrk-endpointwhat-it-does"><colgroup><col></col><col></col></colgroup><tbody><tr><th>Endpoint

</th><th>What it does

</th></tr><tr><td>`<span class="editor-theme-code">POST /v1/carts/{cartId}/add</span>`

</td><td>Add items to a cart

</td></tr><tr><td>`<span class="editor-theme-code">POST /v1/carts/{cartId}/change</span>`

</td><td>Change item quantities

</td></tr><tr><td>`<span class="editor-theme-code">POST /v1/carts/{cartId}/remove</span>`

</td><td>Remove items

</td></tr></tbody></table>

Their request bodies look pretty familiar. Each one sends a list of `<span class="editor-theme-code">items</span>`, and each item has a `<span class="editor-theme-code">variantId</span>` and a `<span class="editor-theme-code">quantity</span>`. So today's idea (the cart cares about the variant, not the product) carries straight over.

What comes back is the whole cart. Each item has a `<span class="editor-theme-code">variant</span>` (with its own `<span class="editor-theme-code">id</span>`, `<span class="editor-theme-code">name</span>`, and `<span class="editor-theme-code">unitPrice</span>`) and a `<span class="editor-theme-code">quantity</span>`. There's no subtotal field in the cart response, so any total you add up in the browser is only an estimate. The real total comes from checkout.

A few things change once the cart is on a server:

1. The click sends a request. In the version we'll build, the page waits for the answer before changing the cart.
2. The server can say no (out of stock, bad quantity), so you show the error and keep the last cart that actually worked.
3. You update the page from the cart the server sends back, not from the number you *hoped* it would be.
4. While a request is going, you disable the cart buttons so two changes don't race each other. (Same idea as disabling **Load interests** last week.)

And a cart still isn't an order, whether it's ours or Fourthwall's. Next week, we'll follow it from the cart into checkout and see what happens to payment and orders.

## When something goes wrong

<table id="bkmrk-what-you-seewhat-to-"><colgroup><col></col><col></col></colgroup><tbody><tr><th>What you see

</th><th>What to check

</th></tr><tr><td>The page goes blank and the Console says

`<span class="editor-theme-code">useState is not defined</span>`

</td><td>Add the import from Step 1 at the top of

`<span class="editor-theme-code">App.jsx</span>`

, with the other imports (not inside

`<span class="editor-theme-code">App</span>`

).

</td></tr><tr><td>Clicking does nothing and the Console says

`<span class="editor-theme-code">cart is not defined</span>`

 or

`<span class="editor-theme-code">setCart is not defined</span>`

</td><td>The function got pasted outside

`<span class="editor-theme-code">App</span>`

 (after its last

`<span class="editor-theme-code">}</span>`

). Move it inside

`<span class="editor-theme-code">App</span>`

, above

`<span class="editor-theme-code">return (</span>`

.

</td></tr><tr><td>A red error about an unexpected token or

`<span class="editor-theme-code">}</span>`

</td><td>Usually a paste landed inside the wrong tag or a brace went missing. Compare that spot with the snippet, or grab the catch-up copy for the step you're on.

</td></tr><tr><td>The dropdown changes, but Add uses the wrong size

</td><td>The

`<span class="editor-theme-code">select</span>`

 should read and set

`<span class="editor-theme-code">selectedVariantId</span>`

, and

`<span class="editor-theme-code">AddButton</span>`

 should get that same ID.

</td></tr><tr><td>Same size twice still makes two lines

</td><td>The

`<span class="editor-theme-code">existingLine</span>`

 check from Step 2 has to come before the

`<span class="editor-theme-code">setCart([...cart, ...])</span>`

 at the bottom of

`<span class="editor-theme-code">handleAdd</span>`

, and it needs its

`<span class="editor-theme-code">return;</span>`

 after the

`<span class="editor-theme-code">cart.map</span>`

 part. Without that

`<span class="editor-theme-code">return</span>`

, both

`<span class="editor-theme-code">setCart</span>`

 calls run and the second one wins.

</td></tr><tr><td>Small and Medium become one line

</td><td>Check the

`<span class="editor-theme-code">existingLine</span>`

 find in

`<span class="editor-theme-code">handleAdd</span>`

. It has to compare

`<span class="editor-theme-code">line.variantId === variantId</span>`

, not the product ID.

</td></tr><tr><td>The page goes blank with "Too many re-renders" in the Console

</td><td>Something is calling a function while React draws the page. Pass the function (

`<span class="editor-theme-code">onAdd={handleAdd}</span>`

), and wrap the others in an arrow, like

`<span class="editor-theme-code">() => handleAdd(selectedVariantId)</span>`

.

</td></tr><tr><td>You click Add and the cart stays empty, with no error

</td><td>Check Remove's

`<span class="editor-theme-code">onClick</span>`

. Without the arrow,

`<span class="editor-theme-code">handleRemove(line.variantId)</span>`

 runs while the line is being drawn, so it removes itself instantly.

</td></tr><tr><td>Clicking does nothing to the cart

</td><td>Make a new array or object and call

`<span class="editor-theme-code">setCart</span>`

. If you edit the old one with

`<span class="editor-theme-code">push</span>`

 or

`<span class="editor-theme-code">existingLine.quantity = 2</span>`

, React may not notice anything changed.

</td></tr><tr><td>The price is 100 times too big

</td><td>The data is in cents. Divide by 100 only once, in

`<span class="editor-theme-code">formatPrice</span>`

.

</td></tr><tr><td>The cart is empty after refreshing

</td><td>That's expected. This cart only lives in React state.

</td></tr></tbody></table>

## Resources

Everything needed for today's code and explanations is above. These are extra examples or references to return to after the exercise.

- [React: Sharing State Between Components](https://react.dev/learn/sharing-state-between-components)
- [React: Responding to Events](https://react.dev/learn/responding-to-events)
- [React: Updating Arrays in State](https://react.dev/learn/updating-arrays-in-state)
- [React: Updating Objects in State](https://react.dev/learn/updating-objects-in-state)
- [React: `<span class="editor-theme-code"><select></span>`](https://react.dev/reference/react-dom/components/select)
- [React: Rendering Lists (keys)](https://react.dev/learn/rendering-lists)
- [MDN: Array.find](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/find)
- [MDN: Array.filter](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/filter)
- [MDN: Array.map](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map)
- [MDN: Spread syntax](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Spread_syntax)
- [MDN: Arrow functions](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions)
- [Fourthwall: Add to Cart](https://docs.fourthwall.com/api-reference/storefront/carts/add-to-cart)
- [Fourthwall: Change Cart Quantity](https://docs.fourthwall.com/api-reference/storefront/carts/change-cart-quantity)
- [Fourthwall: Remove from Cart](https://docs.fourthwall.com/api-reference/storefront/carts/remove-from-cart)