Project
Menu Browser
Goal: Build a real, clickable React app - a restaurant menu browser with search, a category filter, per-dish quantity validation, and an add-to-cart counter with a running ₹ total. Time: ~5 hours · Uses: Parts 1-5 only (no
fetch, nouseEffect- this project proves the foundation stage before Stage 2 adds either)
Project brief
Rohan's Tiffin Center - the same restaurant Part 4's MenuBrowser example already searched - wants a bigger menu online: ten dishes across four categories, a way to filter by category on top of the existing search box, a quantity field per dish (so a customer can order more than one Masala Dosa at a time, within reason), and a running cart total so a customer can see what they owe before checking out.
This demo runs against the menu in data.js (ten dishes, two of them out of stock):
Search: "dosa" → Masala Dosa, ₹90
Category: Beverages → Filter Coffee ₹40, Masala Chai ₹25
Quantity for Masala Dosa: 3, Add → Cart: 3 item(s) · ₹270
Quantity for Veg Biryani: anything → "Out of stock" button, always disabled
Files
| File | What it is |
|---|---|
README.md |
This brief and the step-by-step build guide |
data.js |
The ten-dish menu (tiffinMenu) and the four category names, both exported for reuse |
MenuBrowser.jsx |
Complete reference implementation (try building your own first!) |
MenuBrowser.test.jsx |
The verified test suite - every behavior below is actually run, not just described |
How to run
This project reuses the one repo-level harness (Node 22, npm 11, Vitest + Testing Library - see ../../TOOLING.md) - no separate install, no separate package.json. From the repo root:
npx vitest run stage-1-foundation/project-menu-browser
To actually see it render, add <MenuBrowser /> to harness/src/App.jsx temporarily (import it from this folder) and run npm run dev - then remove the import again once you are done, so the harness keeps showing whichever part it is currently wired for.
Features
| Feature | What it does |
|---|---|
| Menu list | Every dish in data.js, rendered with .map() and a stable item.id key |
| Search | A controlled text input filters the visible list by name as you type |
| Category filter | A controlled <select> filters the visible list by category; combines with search (both filters apply at once) |
| Out-of-stock dishes | Render with a disabled "Out of stock" button and a disabled quantity field - never addable, no matter what |
| Quantity field | A controlled, per-dish text field (inputMode="numeric"), validated as a whole number from 1 to 10 |
| Add to cart | Enabled only when the dish is in stock and its quantity is valid; adds that many of that dish to one shared cart |
| Cart summary | One line, always visible: Cart: <count> item(s) · ₹<total>, built from a single { count, total } state object |
| Empty state | A real message (not a blank list) when search + category together match nothing |
Which Parts each feature uses
| Feature | Skills | Part |
|---|---|---|
The dish list, .map(), stable item.id keys |
Rendering lists, keys | Part 4 |
| Search box filtering as you type, the empty state | .filter() feeding .map(), ternary at the list's root |
Part 4 |
| Out-of-stock button/field, disabled styling | Conditional rendering, disabled prop |
Part 4 |
Category <select> |
Controlled select (value/onChange) |
Part 5 |
| Per-dish quantity field + inline error | Controlled text input, validation derived fresh on every render (not stored separately) | Part 5 |
Add button's disabled expression |
Disabled-until-valid pattern | Part 5 |
Cart { count, total } object, updated immutably per click |
useState, object spread, functional updates |
Part 3 |
One quantity string per dish, in one object-shaped state (quantities) |
Single-object multi-field state | Part 5 |
MenuBrowser({ items, categories }) as one composed component |
Props, composition | Part 2 |
💡 No
fetch, nouseEffect, no router, no context, no reducer - every one of those is a later part or stage. This project's whole point is proving Parts 1-5 are enough to ship something real and interactive.
Build it step by step
Build in small steps. Run the tests after every step. Do not open MenuBrowser.jsx until you have tried each step yourself.
Step 1: The data (Part 2)
What and why: a menu is just data - no component needs to "know" about ten specific dishes by name.
// data.js
export const categories = ["All", "Breakfast", "Main Course", "Beverages", "Snacks"];
export const tiffinMenu = [
{ id: "d1", name: "Masala Dosa", price: 90, category: "Breakfast", inStock: true },
// ...
];
Give each dish a stable id (never the array index - Part 4, section 3's bug), a category that matches one of the categories strings exactly, and an inStock boolean.
✅ Test: tiffinMenu.length is 10; two dishes have inStock: false.
Step 2: Render the list (Part 4)
What and why: before any filtering exists, get every dish on screen with the right key.
<ul>
{items.map((item) => (
<li key={item.id}>
<span>{item.name}</span> <span>{`₹${item.price}`}</span>
</li>
))}
</ul>
✅ Test: render <MenuBrowser /> and confirm all 10 dish names appear.
Step 3: Search (Part 4)
What and why: reuse Part 4's own MenuBrowser example exactly - a controlled input, .filter() by lowercase substring, feeding the same .map() from Step 2.
const [query, setQuery] = useState("");
const visibleByName = items.filter((item) => item.name.toLowerCase().includes(query.trim().toLowerCase()));
✅ Test: typing "coffee" leaves exactly one dish visible.
Step 4: Category filter (Part 5)
What and why: a second, independent filter, run before the search filter (order between two .filter() calls on different fields does not matter here - both must pass).
const [selectedCategory, setSelectedCategory] = useState("All");
const visibleItems = items
.filter((item) => selectedCategory === "All" || item.category === selectedCategory)
.filter((item) => item.name.toLowerCase().includes(query.trim().toLowerCase()));
The dropdown itself is a controlled <select>, exactly like Part 5, section 3's DeliveryCityDropdown - value={selectedCategory}, onChange sets it from event.target.value, one <option> per category string (including "All").
✅ Test: choosing "Beverages" leaves exactly the two beverage dishes visible; combining it with a search term narrows further.
Step 5: The empty state (Part 4)
What and why: search and category together can leave nothing - say so explicitly.
{visibleItems.length === 0 ? (
<p className="empty-state">{`No dishes match "${query}" in ${selectedCategory === "All" ? "any category" : selectedCategory}.`}</p>
) : (
<ul>{/* Step 2-4's list */}</ul>
)}
✅ Test: searching "pizza" (which matches nothing) shows the empty-state message and renders zero <li>s.
Step 6: Out-of-stock dishes (Part 4)
What and why: an out-of-stock dish should never be addable, however the cart eventually works.
<button disabled={!item.inStock}>{item.inStock ? "Add" : "Out of stock"}</button>
✅ Test: both out-of-stock dishes render a disabled "Out of stock" button; the other eight render an enabled "Add".
Step 7: Per-dish quantity, with validation (Part 5)
What and why: before "Add" can mean anything beyond "add one," each dish needs its own quantity, held as a string (what a text input always gives you) in one object-shaped state - one useState call for every dish's quantity, matching Part 5, section 2's single-object pattern instead of ten separate useState calls:
const [quantities, setQuantities] = useState(() =>
Object.fromEntries(items.map((item) => [item.id, "1"])),
);
function handleQuantityChange(itemId, rawValue) {
setQuantities((current) => ({ ...current, [itemId]: rawValue }));
}
Validate the current string on every render - Part 5, section 5's "derive, don't duplicate" rule, the same reason isFormIncomplete was never its own useState there:
function validateQuantity(rawValue) {
if (rawValue.trim() === "") return "Enter a quantity.";
if (!/^\d+$/.test(rawValue.trim())) return "Quantity must be a whole number.";
const quantity = Number(rawValue.trim());
if (quantity < 1 || quantity > 10) return "Quantity must be between 1 and 10.";
return null;
}
✅ Test: clearing a dish's quantity field shows "Enter a quantity."; typing "11" shows "Quantity must be between 1 and 10."; typing "abc" shows "Quantity must be a whole number."
Step 8: Wire quantity validation into the Add button (Part 5)
What and why: "Add" needs to be disabled for two independent reasons now - out of stock (Step 6), or an invalid quantity (Step 7) - combined the same way Part 5, section 5's gift-card exercise combined two disabled-reasons into one boolean.
const quantityError = validateQuantity(quantities[item.id] ?? "1");
const addDisabled = !item.inStock || quantityError !== null;
✅ Test: an in-stock dish with an invalid quantity shows a disabled "Add" for that row only - every other row's "Add" stays enabled.
Step 9: The cart (Part 3)
What and why: one shared { count, total } object, updated immutably on every "Add" click - the same object-state-update shape Part 3's cart examples already used, never mutated in place.
const [cart, setCart] = useState({ count: 0, total: 0 });
function handleAdd(item) {
const quantity = Number(quantities[item.id]);
setCart((current) => ({
count: current.count + quantity,
total: current.total + item.price * quantity,
}));
}
✅ Test: adding 3 Masala Dosas (₹90 each) shows "Cart: 3 item(s) · ₹270"; adding a second, different dish afterward adds to the same total instead of replacing it.
Stretch goals
- 🟢 A "Clear search" button that resets
queryto""in one click. - 🟢 Sort the visible list by price, with a second controlled
<select>("Sort by: name / price"). - 🟡 A per-dish "remove last add" undo, without touching which dish was added (keep a small history array in state).
- 🟡 Show each dish's own running subtotal (
price × last-added quantity) next to the Add button, recomputed the same derive-don't-duplicate way as Step 7's validation. - 🔴 A checkout
<form>withonSubmit/preventDefaultthat reads the finalcart.totaland shows a "Thank you" confirmation - the sign-up form shape from Part 5, section 7, repurposed for checkout. - 🔴 Persist the cart in
localStorageso it survives a refresh - a deliberate stretch outside this stage's scope, since reading/writing outside React's own state isuseRef/custom-hook territory (Stage 2, Parts 7-8), not Parts 1-5.
Checklist
- I rendered the full ten-dish menu with
.map()and a stableitem.idkey on every row. - I filtered the list by search text and, independently, by category - and confirmed both filters combine correctly.
- I showed a real empty-state message instead of a blank list when nothing matches.
- I rendered out-of-stock dishes with a permanently disabled "Add" button and quantity field.
- I validated a per-dish quantity field on every render (not on a separate submit step), with the three error messages from Step 7 all reproducible.
- I disabled "Add" for two independent reasons (out of stock, invalid quantity) combined into one boolean, without storing that boolean separately from the state it depends on.
- I updated a single
{ count, total }cart object immutably on every "Add" click, and confirmed it accumulates across multiple different dishes. -
npx vitest run stage-1-foundation/project-menu-browserpasses, start to finish, with nofetchand nouseEffectanywhere in the file.
Next
🎉 Stage 1 done! Go back to the roadmap and start Stage 2, Part 6: useEffect and side effects.