Sorting by clicking a column header is a small design exercise: what is the state, and what is derived?
What to build
A table of products whose headers sort it.
Requirements
- Keep
PRODUCTS. Render atablewith header buttonsNameandPrice(insidethelements) and onetrper product in the body with the name and the price. - At first the table is in the data's order. Clicking a header sorts by that column ascending; clicking the same header again reverses the order. The active header's
thhasaria-sortset toascendingordescending; the other has noaria-sort.
Constraints
Do not store the sorted list in state.
Example
Clicking Price shows Pen, Notebook, Bag; clicking it again shows Bag, Notebook, Pen.
Why it works
Only the sort column and direction change and cannot be computed, so they are the state, and the rows are sorted from a copy of the data on each render.
Hints
Hint 1
State: which column and which direction. The sorted rows are computed from them.
Hint 2
Clicking the current column flips the direction; clicking another column sorts it ascending.
Solution
Show one correct solution (try it yourself first)
import { useState } from "react";
const PRODUCTS = [
{ name: "Notebook", price: 4.5 },
{ name: "Bag", price: 40 },
{ name: "Pen", price: 1.2 },
];
export default function App() {
const [sort, setSort] = useState(null); // { key, dir } or null
function sortBy(key) {
setSort(sort && sort.key === key ? { key, dir: sort.dir === "ascending" ? "descending" : "ascending" } : { key, dir: "ascending" });
}
let rows = PRODUCTS;
if (sort) {
const sign = sort.dir === "ascending" ? 1 : -1;
rows = [...PRODUCTS].sort((a, b) => sign * (sort.key === "price" ? a.price - b.price : a.name.localeCompare(b.name)));
}
const header = (key, label) => (
<th aria-sort={sort && sort.key === key ? sort.dir : undefined}>
<button onClick={() => sortBy(key)}>{label}</button>
</th>
);
return (
<table>
<thead>
<tr>
{header("name", "Name")}
{header("price", "Price")}
</tr>
</thead>
<tbody>
{rows.map((p) => (
<tr key={p.name}>
<td>{p.name}</td>
<td>{p.price}</td>
</tr>
))}
</tbody>
</table>
);
}