Week 8
Last week, we built a cart. Today, we're taking it somewhere new: the real Blueprint website. So far, everything we've built lived in a Vite and React project on your own computer. The Blueprint site is built differently, so the first part of today is about what changed and why. After that, we'll split into teams and write some code together.
By the end of the meeting, you'll have added a Store page to a practice copy of the Blueprint website. It shows last week's made-up products, lets you pick a size, add things to a cart, and remove them. Nothing on it is for sale, the cart only lives on the page (refreshing empties it), and nothing you change touches the live site.
What is different about the real site?
The Blueprint website is still HTML, CSS, JavaScript, and React, so you already know most of what's in it. What's different is the tooling around it.
| Weeks 1 to 7 | The Blueprint website | |
|---|---|---|
| What runs the tools | Node.js | Deno (version 2) |
| What builds the page | Vite | Lume |
| Installing packages | npm install |
Nothing, Deno downloads what it needs the first time you start it |
| Start it | npm run dev |
deno task serve |
| Address | Vite prints one (usually http://localhost:5173) | http://localhost:3000, and it opens the browser for you |
| Settings | package.json, vite.config.js |
deno.json and _config.ts |
| Pages | One App.jsx |
Every .md file in src/ is a page |
| Where the words go | Inside the JSX | At the top of the .md file |
| Styling | Plain CSS in App.css |
Tailwind classes in the JSX |
| Where React runs | In the browser, every time something changes | Once, when the site is built |
useState and onClick |
Work | Do nothing |
| Finished version | npm run build |
deno task build |
We'll go through the big ones.
What is Deno?
Deno is another JavaScript runtime, just like Node.js. It runs JavaScript (and TypeScript) on your computer, outside the browser. The Blueprint website runs on Deno, so that's what starts when you type deno task serve.
You still need Node.js. The site uses npm for one thing, a formatting tool called Prettier.
What is Lume?
Lume is a static site generator. It takes the files in src/ and turns them into a website made of plain HTML and CSS files. Open deno.json and look at tasks:
"build": "deno task lume",
"serve": "deno task lume -s"
deno task serve builds the site and starts a local server. deno task build builds it into the output/ folder, which is the finished site. These are the same idea as the scripts in package.json from Weeks 1 to 7.
The live site is hosted as plain files, so there's no server running our code when someone visits. Whatever Lume builds is all the visitor gets.
How do pages work?
In Weeks 1 to 7, App.jsx was the whole page. Here, the page /about comes from the file src/about.md. At the top of that file, you'll see this:
---
title: About | Blueprint
layout: _layouts/About.jsx
hero:
title: About Us
description: >
We are the Stevens Institute of Technology chapter of Blueprint ...
---
This part is called front matter. It's data: a title, which layout to use, and the words for the page. The layout line points to src/_includes/_layouts/About.jsx, which is a React component. Lume hands it the front matter as props, so hero.title in the JSX is the "About Us" you see above. It's the same idea as a card getting a title prop in Week 4, except these props come from the top of a file.
The site's docs ask us to keep the words in the .md files and use the JSX just for how it looks, so we'll do that too.
Where does React run?
This is the biggest difference.
In Weeks 1 to 7, React ran in your browser. When setCart ran, React redrew the page. On this site, React runs on your computer, once, while Lume builds the site. It turns your JSX into HTML and stops. The browser never gets React.
That's great for things like "make one card for each product". But useState can't remember anything, because the page is already finished before anyone clicks. And onClick does nothing. Lume leaves the handler out of the HTML completely, and it doesn't tell you. We tried a button with onClick={() => alert("hi")}, and it came out as a plain <button>.
So we can't copy last week's cart over. What carries over is the thinking: components, props, .map() with a key, .find(), spread, and .filter(). The part that has to happen when someone clicks, we'll write as a small plain JavaScript file using addEventListener, like Week 2. It's more work, and that's pretty much why React exists.
Here's a way to keep the two halves straight:
| Runs when the site is built | Runs in the browser |
|---|---|
The .md front matter, layouts, and components (.jsx) |
Files in src/assets/js/, loaded with a <script> tag |
Makes one card per product with .map() |
Reacts to a click and changes the cart |
What is Tailwind?
Instead of writing CSS in a separate file, this site puts small classes right on the elements. className="text-2xl font-bold text-primary" means big, bold, and the Blueprint blue. primary and secondary are colors set in _config.ts. You don't need to memorize any of them. The Tailwind docs have a search box.
How does a change get onto the real site?
On the real repo, merging to main starts a GitHub Action that builds the site and puts it on the live site. Because of that, the club has an approval process. A change that looks different needs a review from the Website Team and the Design Team before it merges.
That's why we're working in a practice copy today. You can't break sitblueprint.com from here. If the Store page turns out well, getting it onto the real site would go through that process.
Teams
We'll split into teams here. Sit with your team for the rest of the meeting. We'll write the first page together on our own computers, and after that, your team picks tickets from the repo's Issues tab.
Getting started
You should have already installed Deno and cloned the practice copy from the Setup page. Open a terminal in that folder (not inside practice-page) and make a new branch for today:
git switch -c store-page
If Git says that branch already exists, use git switch store-page instead. Then start the site:
deno task serve
Your browser should open the Blueprint homepage at http://localhost:3000. The terminal will show some yellow warnings (about deprecated packages, charset, defaultProps). Those come from the real site's code and don't mean anything is broken. The line that matters ends with Server started at: http://localhost:3000/.
Leave the server running the whole time. Every time you save, it rebuilds and the page refreshes by itself. If deno isn't found, check the Setup page.
Here's what we'll build:
| Step | What you add | What you'll see |
|---|---|---|
| 1 | A page, a layout, and a navbar link | A Store page with a heading |
| 2 | A product card | Three cards, made from the fixtures |
| 3 | A size dropdown | Sold-out sizes greyed out |
| 4 | An Add to cart script | A cart that grows and counts |
| 5 | A Remove button | A cart you can empty |
Step 1: Add the page
We need two files and one line. Pages are .md files, so let's make one. Create src/store.md:
---
title: Store | Blueprint
layout: _layouts/Store.jsx
---
That's the whole file for now. Next, the layout it points to. Create src/_includes/_layouts/Store.jsx:
export default ({ comp, title }) => (
<html>
<head>
<comp.GoogleAnalytics />
<comp.OpenGraphCommon />
<link rel="stylesheet" href="/styles.css" />
<meta
name="viewport"
content="width=device-width, initial-scale=1.0"
></meta>
<title>{title}</title>
</head>
<body>
<comp.Navbar alternate={true} />
<main className="mx-auto max-w-5xl px-6 py-10">
<h1 className="text-4xl font-bold text-primary">Store</h1>
<p className="mt-2 text-xl">
Made-up products for practice. Nothing here is for sale.
</p>
</main>
<comp.Footer />
</body>
</html>
);
We copied this from Blog.jsx, which sits next to it. A layout is a whole page, so unlike the components from Week 4, it has <html>, <head>, and <body>. title comes from store.md, and comp is how we reach the shared navbar and footer.
Save. Go to http://localhost:3000/store/ (the slash at the end matters). You should see the navbar, the heading Store, and the footer. If you get a 404, check that the file is src/store.md and that the layout: line matches the layout's filename exactly.
Now let's make it easy to find. Open src/_components/Navbar.jsx and add one line to the navigationLinks list at the top:
{ href: "/blog", text: "Blog" },
{ href: "/store", text: "Store" },
Save. Store shows up in the navbar on every page, because the navbar is one shared component.
That's how you add a page here: a .md file, a layout for it, and a link. (Blog posts and project pages have their own steps in the site's docs/DOCS.md.)
Step 2: Product cards
Our products need to come from somewhere. On this site, content goes in the front matter, so open src/store.md and replace it with this. The products part is also in practice/store-fixtures.yml if you'd rather copy it:
---
title: Store | Blueprint
layout: _layouts/Store.jsx
hero:
title: Store
description: Made-up products for practice. Nothing here is for sale.
products:
- id: fixture-tee
name: Practice T-shirt
slug: practice-t-shirt
imageUrl: /assets/practice/practice-tee.svg
variants:
- id: fixture-tee-small
name: Small
price: 24
currency: USD
available: true
- id: fixture-tee-medium
name: Medium
price: 24
currency: USD
available: true
- id: fixture-tee-large
name: Large
price: 24
currency: USD
available: false
- id: fixture-hoodie
name: Practice Hoodie
slug: practice-hoodie
imageUrl: /assets/practice/practice-hoodie.svg
variants:
- id: fixture-hoodie-medium
name: Medium
price: 45
currency: USD
available: true
- id: fixture-hoodie-large
name: Large
price: 45
currency: USD
available: true
- id: fixture-stickers
name: Practice Sticker Pack
slug: practice-sticker-pack
imageUrl: null
variants:
- id: fixture-stickers-one
name: One size
price: 7.5
currency: USD
available: true
---
This is the same product and variant idea from Week 7. A product has variants, and each variant has its own id, a name, a price, and available. A few names changed (name instead of label, price instead of priceMinor) so they match the shape we'll use for the real store. Two other things are different:
priceis dollars, not cents.24means $24.00 and7.5means $7.50, so there's no dividing by 100 today.- The sticker pack has
imageUrl: null. It has no picture on purpose, and we'll see what that does in a second.
Now the card. Make a folder src/_components/Store, and make a file inside it called ProductCard.jsx:
function formatMoney(amount, currency) {
return new Intl.NumberFormat("en-US", { style: "currency", currency }).format(
amount,
);
}
export default function ProductCard({ product }) {
const first = product.variants[0];
return (
<article className="flex flex-col gap-3 rounded-2xl border border-secondary p-4">
<img
src={product.imageUrl}
alt={product.name}
className="aspect-square w-full rounded-xl object-cover"
/>
<h2 className="text-2xl font-bold text-primary">{product.name}</h2>
<p>{formatMoney(first.price, first.currency)}</p>
</article>
);
}
This is a Week 4 component. It gets a product prop and draws one card. Intl.NumberFormat turns 24 into $24.00.
Last, use it in the layout. In Store.jsx, change the first line so the layout receives the front matter:
export default ({ comp, title, hero, products }) => (
Then replace the heading and paragraph inside <main> with this:
<h1 className="text-4xl font-bold text-primary">{hero.title}</h1>
<p className="mt-2 text-xl">{hero.description}</p>
<div className="mt-8 grid gap-6 sm:grid-cols-2 lg:grid-cols-3">
{products.map((product) => (
<comp.Store.ProductCard key={product.id} product={product} />
))}
</div>
Save. You should see three cards: Practice T-shirt $24.00, Practice Hoodie $45.00, and Practice Sticker Pack $7.50. The sticker pack has a broken picture icon. That's expected, since we told it there's no image. We'll leave that for a ticket.
So what did we just write? products.map(...) is the same .map() from Week 5, making one card per product, and key is the product's id. comp.Store.ProductCard is the file we just made. The folder name Store and the file name ProductCard become the path. grid, gap-6, and lg:grid-cols-3 are Tailwind classes that mean "put these in a grid, three across on a wide screen".
Try changing Practice T-shirt to something else in store.md and save. The card changes, and we didn't touch any code.
Step 3: Pick a size
Each card needs a dropdown of sizes. In Week 7, this was a controlled input with useState. Here, the browser already remembers which <option> is selected, so the card only has to draw the options. No state needed.
Open ProductCard.jsx. Delete the const first = ... line and the blank line under it. Then replace the <article ...> line with this:
<article
className="flex flex-col gap-3 rounded-2xl border border-secondary p-4"
data-product-name={product.name}
>
(data-product-name stores the name on the element so our script can read it in the next step.) Now replace the <p> line that shows first.price with the dropdown:
<label htmlFor={`size-${product.id}`}>Size</label>
<select
id={`size-${product.id}`}
className="rounded border border-primary p-2"
>
{product.variants.map((variant) => (
<option
key={variant.id}
value={variant.id}
disabled={!variant.available}
data-variant-name={variant.name}
data-price-label={formatMoney(variant.price, variant.currency)}
>
{variant.name}, {formatMoney(variant.price, variant.currency)}
{!variant.available && " (sold out)"}
</option>
))}
</select>
Save. Each card has a Size dropdown, and the T-shirt's Large is greyed out with "(sold out)".
This is the Week 7 dropdown again. We .map() over the variants to make one <option> each, and each value is the variant ID, so renaming "Small" to "S" wouldn't matter. !variant.available flips a Boolean, and && shows "(sold out)" only when it's true. The data- lines tuck the variant's name and its price text onto each option. We'll read them in a minute.
Notice there's no value={...} and no onChange. We can't have them, because there's no state. The browser keeps track of the selected option on its own.
Step 4: Add to cart
Now we cross over to the browser. The cart has to change when someone clicks, and only plain JavaScript can do that here.
First, give each card a button. In ProductCard.jsx, put this right after the closing </select>:
<button
type="button"
data-add-to-cart
className="rounded-lg bg-primary px-4 py-2 font-bold text-white"
>
Add to cart
</button>
data-price={variant.price}
data-currency={variant.currency}
Next, a place on the page for the cart. In Store.jsx, add a script tag to the <head>, right above <title>:
<script src="/assets/js/store.js" defer></script>
Then add the cart section inside <main>, right after the </div> that closes the product grid:
<section aria-labelledby="cart-heading" className="mt-12">
<h2 id="cart-heading" className="text-3xl font-bold text-primary">
Your cart
</h2>
<p id="cart-empty" className="mt-2">
Your cart is empty.
</p>
<ul id="cart-lines" className="mt-4 flex flex-col gap-3"></ul>
</section>
And add this right after </main>. It's a <template>, which the browser keeps hidden until a script copies it:
<template id="cart-line-template">
<li className="flex flex-col gap-1 rounded-xl border border-secondary p-4">
<span data-field="name" className="text-xl font-bold"></span>
<span data-field="price"></span>
<span data-field="quantity"></span>
</li>
</template>
We use a template so the classes stay in the JSX, where we're used to them. The script only has to fill in the words.
Now the script. Create the folder src/assets/js and a file in it called store.js:
// Runs in the browser. (Everything in _components and _layouts ran at build time.)
let cart = [];
const emptyMessage = document.querySelector("#cart-empty");
const cartList = document.querySelector("#cart-lines");
const lineTemplate = document.querySelector("#cart-line-template");
function handleAdd(card) {
const option = card.querySelector("select").selectedOptions[0];
setCart([
...cart,
{
variantId: option.value,
productName: card.dataset.productName,
variantName: option.dataset.variantName,
quantity: 1,
unitPrice: Number(option.dataset.price),
currency: option.dataset.currency,
priceLabel: option.dataset.priceLabel,
},
]);
}
function setCart(newCart) {
cart = newCart;
renderCart();
}
function renderCart() {
emptyMessage.hidden = cart.length > 0;
cartList.replaceChildren();
for (const line of cart) {
const item = lineTemplate.content.firstElementChild.cloneNode(true);
item.dataset.variantId = line.variantId;
item.querySelector('[data-field="name"]').textContent =
`${line.productName}, ${line.variantName}`;
item.querySelector('[data-field="price"]').textContent =
`${line.priceLabel} each`;
item.querySelector('[data-field="quantity"]').textContent =
`Quantity: ${line.quantity}`;
cartList.append(item);
}
}
document.addEventListener("click", (event) => {
const addButton = event.target.closest("[data-add-to-cart]");
if (addButton) {
handleAdd(addButton.closest("article"));
}
});
Save and refresh. Pick Small and click Add to cart. You should see "Practice T-shirt, Small", "$24.00 each", and "Quantity: 1". Add the hoodie too, and the cart gets a second line.
Let's match this up with Week 7:
let cart = []isconst [cart, setCart] = useState([]), minus the magic.handleAddis the samehandleAdd.[...cart, newLine]is the same spread idea: make a new array instead of changing the old one.setCart(newCart)is a function we wrote ourselves. It saves the new cart, and then callsrenderCart(). That second line is the part React used to do for us. Nothing here redraws the page automatically, so every time the cart changes, we have to tell the page to redraw it.renderCartempties the list and builds one<li>per cart line, copied from the template. It's thecart.map(...)from Week 7, written out by hand.- The click listener is on the whole
document, andclosest(...)finds the button that was clicked. Week 2 putaddEventListeneron one button. This is the same call. datasetreads thedata-labels from the JSX. Everything indatasetis text, so"24"would be a string. We wrap the price inNumber(...)to get the number24.
Two lines?
Now click Add to cart twice on the same size. You'll see two Small lines, each with Quantity: 1. Open the Console (right-click, Inspect, Console). There's no warning this time. In Week 7, React told us about two children with the same key, but React isn't in the browser here, so nothing is checking our work. That's one more difference.
It's the same bug as Week 7. handleAdd always adds a new line. Refresh to empty the cart, then fix it. Replace handleAdd with this:
function handleAdd(card) {
const option = card.querySelector("select").selectedOptions[0];
const variantId = option.value;
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: variantId,
productName: card.dataset.productName,
variantName: option.dataset.variantName,
quantity: 1,
unitPrice: Number(option.dataset.price),
currency: option.dataset.currency,
priceLabel: option.dataset.priceLabel,
},
]);
}
This is the same fix as Week 7. Look for a line with the same variant ID. If there is one, make a new cart where its quantity is 1 higher, and stop. If there isn't, add a new line.
Save, refresh, and add Small twice. You should see one line with Quantity: 2. Add Medium and you get a second line. If Small and Medium ever share a line, something is comparing product names instead of variant IDs.
Step 5: Remove an item
Each line needs a Remove button that knows which line it's on. In Store.jsx, add the button inside the <li> of the template, under the quantity <span>:
<button
type="button"
data-remove
className="w-fit rounded-lg border border-maroon px-3 py-1 text-maroon"
>
Remove
</button>
In store.js, add handleRemove above the click listener:
function handleRemove(variantId) {
setCart(cart.filter((line) => line.variantId !== variantId));
}
Then change the click listener so it reads:
document.addEventListener("click", (event) => {
const addButton = event.target.closest("[data-add-to-cart]");
if (addButton) {
handleAdd(addButton.closest("article"));
}
const removeButton = event.target.closest("[data-remove]");
if (removeButton) {
handleRemove(removeButton.closest("li").dataset.variantId);
}
});
Save. Add a few things and click Remove on one line. The others stay. Remove them all and "Your cart is empty." comes back.
handleRemove is Week 7's .filter() line: keep every line whose variant ID isn't the one we're removing. How does the button know its line? In renderCart, we put item.dataset.variantId = line.variantId on each <li>. The listener walks up from the clicked button to its <li> with closest("li") and reads the ID back.
Tickets
After the walkthrough, we all switch to the same version of the page so your team's work fits together. The facilitator puts the finished page on main. Run this to get it:
git switch main
git pull
Your store-page branch stays on your computer if you want to compare. Then open the repo's Issues tab. Each ticket is one small job with a checklist at the bottom called the acceptance check. Start with Ticket 0, which is adding your name to CONTRIBUTORS.md and opening your first pull request. After that, your team claims tickets. CONTRIBUTING.md in the repo has the steps.
When something goes wrong
| What you see | What to check |
|---|---|
deno: command not found |
Close and reopen VS Code, then run deno --version. If it's still missing, check the Setup page. |
The first deno task serve seems stuck |
It's downloading. Give it a few minutes. |
/store/ is a 404 |
The file has to be src/store.md, and its layout: has to match Store.jsx exactly. Use the address with the slash at the end. |
| The terminal shows a red error | Read the first red line. A missing ) or } in a .jsx file is the usual cause. |
comp.Store is undefined |
The folder has to be src/_components/Store and the file ProductCard.jsx. The names are case-sensitive. |
A card shows undefined |
Check the front matter in store.md. Spaces matter in YAML, and each variant's lines have to line up. |
| The sticker pack has a broken picture | That's expected. It has no image on purpose. |
| Add to cart does nothing | Open the Console. A red error usually names the line. Check that store.js is in src/assets/js and that the <script> line is in Store.jsx. |
onClick or useState does nothing |
They can't work here. Use data- labels and addEventListener instead. |
| Small shows up twice | Match lines on variantId, like the fix at the end of Step 4. |
Prices show 24 instead of $24.00 |
Format them with formatMoney. The price in store.md is a plain number. |
| The cart is empty after refreshing | That's expected. The cart only lives on the page. |
Resources
Everything needed for today is above. These are for later.