Sub topic 5
Step 2: Build a static version in React
This chapter assumes you can write a function component, read JSX, and use Array.prototype.forEach. It also assumes you have the component hierarchy from Step 1: FilterableProductTable contains SearchBar and ProductTable, and ProductTable contains ProductCategoryRow and ProductRow.
What "static" means
A static version renders the UI from the data model and nothing else. It has no state and no event handlers. Each component receives props and returns JSX.
Building this first keeps the work simple. A static version takes a lot of typing and little thinking. Interactivity takes a lot of thinking and little typing. Doing them separately lets you check that the layout and data mapping are right before you add behavior.
Build from either end of the hierarchy. Small projects are easier from the top down. Larger ones are easier from the bottom up, because you can check each leaf component on its own.
The data
The data model is a flat array. The table has to group it by category.
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 leaf components
ProductCategoryRow renders one heading row. colSpan="2" makes the heading cover both table columns.
ProductRow renders one product. If the product is out of stock, the name is wrapped in a red span. The conditional is an ordinary JavaScript expression assigned to a variable, which keeps the returned JSX easy to read.
function ProductCategoryRow({ category }) {
return (
<tr>
<th colSpan="2">{category}</th>
</tr>
);
}
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>
);
}The table
ProductTable turns the flat array into rows. It walks the products order and remembers the last category it saw. When the category changes, it first pushes a heading row. Then it pushes the product row.
This only works because the array is already ordered by category. The data model guarantees that, and the component relies on it.
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>
);
}Each element p rows has a key. React uses keys to match list items between renders. Here, category names and product names are unique and stable, so they work as keys.
The top level
The top component passes data down as props. The search bar is static for now, so its inputs are plain and have no value or onChange.
function SearchBar() {
return (
<form>
<input type="text" placeholder="Search..." />
<label>
<input type="checkbox" /> Only show products in stock
</label>
</form>
);
}
function FilterableProductTable({ products }) {
return (
<div>
<SearchBar />
<ProductTable products={products} />
</div>
);
}
export default function App() {
return <FilterableProductTable products={PRODUCTS} />;
}Render App in any React project, such as one created with Vite. You should see two category headings, six rows, and the out-of-stock names in red. The inputs show up but do nothing useful yet.
Common errors
- Forgetting
keyon the pushed elements. React logs a warning and may misplace rows when the list changes. - Using the array index as a key. It breaks as soon as rows are filtered or reordered.
- Passing the whole
PRODUCTSarray toProductRow. Each row should receive only the one product it displays. - Writing
colspaninstead ofcolSpan. JSX uses the camelCase DOM property names.
Exercise
In the static version, ProductTable pushes a ProductCategoryRow only when product.category !== lastCategory. What would the table look like if you moved Pumpkin, a Vegetable, between Apple and Dragonfruit in PRODUCTS?
Show answer
The table would show "Fruits", Apple, "Vegetables", Pumpkin, "Fruits", Dragonfruit, and so on. The category changes at each switch, so headings repeat. The grouping logic assumes the data is already sorted by category. Sorting it first, or grouping it in the component, fixes this.