Sub topic 5
Step 2: Build a static version in React
This chapter assumes you can write a function component, read JSX, and pass props. It also assumes you have already split the mockup into a component hierarchy in Step 1. Here you turn that hierarchy into code that renders the table from data, with no state and no interactivity.
Why build a static version first
A static version is a copy of the UI that takes data in and renders it. It has no useState, no event handlers, and no filtering. You build it first because two kinds of work pull in opposite directions:
- Rendering a lot of markup takes a lot of typing and little thinking.
- Adding interactivity takes a lot of thinking and little typing.
Separating them lets you do the typing first, then spend your attention on state in later steps. It also gives you a working baseline. If something breaks later, you know the markup was correct before state was added.
The rule for this step is simple: every component receives data through props and returns JSX. Nothing is stored. Nothing changes.
The data model
The mockup is built from a flat array. Each product has a category, a price, a stock flag, and a name.
const PRODUCTS = [
{ category: 'Fruits', price: '$1', stocked: true, name: 'Apple' },
{ category: 'Fruits', price: '$1', stocked: true, name: 'Dragonfruit' },
{ category: 'Fruits', price: '$2', stocked: false, name: 'Passionfruit' },
{ category: 'Vegetables', price: '$2', stocked: true, name: 'Spinach' },
{ category: 'Vegetables', price: '$4', stocked: false, name: 'Pumpkin' },
{ category: 'Vegetables', price: '$1', stocked: true, name: 'Peas' }
];The array is already sorted so that products in the same category are adjacent. The rendering code below depends on that. If your real data is not grouped, sort it before you render, or the same category heading will appear more than once.
The components you are building
From Step 1, the hierarchy looks like this. Only the table and its two row types are built in this chapter.
SearchBar and FilterableProductTable come in later steps. For now, ProductTable is the root you render.
Build from the bottom up
For a small app like this one, it is easier to start with the leaf components and work upward. In a larger project, building top-down and writing tests as you go can be easier. Either way, start with a component that has no children.
ProductCategoryRow
This component renders one heading row. It takes a single prop, category.
function ProductCategoryRow({ category }) {
return (
<tr>
<th colSpan="2">{category}</th>
</tr>
);
}The colSpan="2" makes the heading cell stretch across both columns of the table, name and price. In JSX, HTML attributes use camelCase, so colspan becomes colSpan.
ProductRow
This component renders one product. Out-of-stock products show their name in red.
function ProductRow({ product }) {
const name = product.stocked ? (
product.name
) : (
<span style={{ color: 'red' }}>{product.name}</span>
);
return (
<tr>
<td>{name}</td>
<td>{product.price}</td>
</tr>
);
}nameholds either a plain string or a JSX element. Both are valid things to put inside{}.styletakes an object, not a string. The outer braces mark a JavaScript expression, and the inner braces are the object literal.- The component reads from
productand nothing else. Given the sameproduct, it always returns the same output.
ProductTable
The table component takes the whole array and builds the list of rows. It must insert a category heading each time the category changes.
function ProductTable({ products }) {
const rows = [];
let lastCategory = null;
products.forEach((product) => {
if (product.category !== lastCategory) {
rows.push(
<ProductCategoryRow
category={product.category}
key={product.category}
/>
);
}
rows.push(<ProductRow product={product} key={product.name} />);
lastCategory = product.category;
});
return (
<table>
<thead>
<tr>
<th>Name</th>
<th>Price</th>
</tr>
</thead>
<tbody>{rows}</tbody>
</table>
);
}Here is how the loop works on the sample data:
lastCategorystarts as so the first product, Apple, differs from it. A "Fruits" heading is pushed, then the Apple row.- Dragonfruit has the same category as
lastCategory, so only its row is pushed. - Passionfruit does the same.
- Spinach has category "Vegetables", which differs from "Fruits". A "Vegetables" heading is pushed, then the Spinach row.
- Pumpkin and Peas add only their rows.
rows ends up as a flat array of eight elements: two headings and six products. React renders an array of elements placed inside JSX.
Keys
Each element pushed into rows has a key prop. React uses keys to match items from one render to the next, so it can tell which entries were added, removed, or moved.
The keys in this example are:
product.categoryfor heading rows.product.namefor product rows.
These work because the values are unique among siblings. A category heading and a product never share a key, and in this data no two products share a name. Keys only need to be unique among siblings in the same list, not across the whole app.
Key rules and common mistakes
| Mistake | What goes wrong | Fix |
|---|---|---|
| No key at all | React logs a warning in development and falls back to position | Add a stable `key` |
| Using the array index as the key on a list that can be reordered or filtered | Rows can keep the wrong state or DOM node after the list changes | Use an ID from the data |
| Generating a key during render, such as `Math.random()` | Every row looks new on every render, so React recreates all of them | Derive the key from the data |
| Two siblings with the same key | Warnings, and updates can be applied to the wrong row | Make keys unique |
| Putting `key` on the element inside a component instead of where the list is built | The key is ignored | Set `key` on the element in the array |
A key is not a prop. Your component cannot read props.key. If a child needs the value, pass it again under another name.
In this data, name is a stable identifier. Real products would have an ID, and you should use that, because two products can share a name.
Render the static version
Put it together by rendering ProductTable with the data.
export default function App() {
return <ProductTable products={PRODUCTS} />;
}You should see a table with a "Fruits" heading and three rows, followed by a "Vegetables" heading and three rows. Passionfruit and Pumpkin are in red.
The search box and checkbox do not exist yet. That is expected.
What "static" means here
The word "static" does not mean the output never changes. It means the component has no memory of its own. Its output is a function of its props:
- Same props in, same JSX out.
- No
useState, nouseReducer, no effects. - No reading from or writing to variables outside the function.
One thing in ProductTable looks like it breaks this rule: rows and lastCategory are changed during the render. This is allowed. They are created inside the function, used there, and thrown away after. React calls this a local mutation. Mutating something that existed before the render, such as the products array, would not be allowed.
Props flow down
Look at what you wrote. App passes products to ProductTable. ProductTable passes a category to each ProductCategoryRow and a product to each ProductRow. Data only moves from parent to child. No child reaches back up.
This is one-way data flow, and the next chapter covers why it matters. For now, notice the practical benefit. If a row shows the wrong price, the bug is in the data passed down or in the row's markup. It is not somewhere else in the app.
Common problems
- A heading appears twice. The data is not grouped by category. Sort it first.
- A warning about keys. Check that every element in
rowshas a key, and that it is on the element you push, not on something nested inside it. - The red style does not show. Check that
stylereceives an object (style={{ color: 'red' }}), not a string. - Headings do not span the table. Use
colSpan, notcolspan. - Nothing renders. Check that the component name starts with a capital letter. React treats lowercase names as HTML tags.
Checklist for this step
- Every component takes props and returns JSX.
- No component calls
useState. - The table renders both categories with correct headings.
- Out-of-stock names are red.
- Every list element has a stable, unique key.
- Nothing from outside the render function is mutated.
Exercise
The products array arrives in this order: Apple (Fruits), Spinach (Vegetables), Dragonfruit (Fruits). What does the current ProductTable render, and what is the smallest change that fixes it? Also, what React warning might you see?
Show answer
It renders three headings: Fruits, Vegetables, Fruits. The check compares each product only with the previous one, so Dragonfruit triggers a second "Fruits" heading. Because that heading reuses the key "Fruits", React warns about two children with the same key. The smallest fix is to group the data by category before rendering, for example with const sorted = [...products].sort((a, b) => a.category.localeCompare(b.category)); and looping over sorted. Copying the array first avoids mutating the prop.
Exercise
Why does ProductTable get away with changing rows and lastCategory during render, when static components are supposed to be free of side effects?
Show answer
Both variables are created inside the function call and discarded after it. Nothing outside the render can observe the change, so the output still depends only on the props. Mutating something created before the render, such as the products prop, would be a real side effect and is not allowed.