Coding exercise: implement sorting and filtering in React.
Model answer
Keep the raw list, the search text and the sort choice in state. Work out the visible list during render, because it is derived data and does not need its own state. Copy before sorting, since sort changes the array it is called on.
function Products({ products }) {
const [q, setQ] = useState('');
const [sort, setSort] = useState('name');
const visible = useMemo(() => {
const list = products.filter((p) => p.name.toLowerCase().includes(q.toLowerCase()));
return [...list].sort((a, b) => (sort === 'price' ? a.price - b.price : a.name.localeCompare(b.name)));
}, [products, q, sort]);
return (
<>
<input value={q} onChange={(e) => setQ(e.target.value)} placeholder="Filter" />
<select value={sort} onChange={(e) => setSort(e.target.value)}>
<option value="name">Name</option><option value="price">Price</option>
</select>
<ul>{visible.map((p) => <li key={p.id}>{p.name} – {p.price}</li>)}</ul>
</>
);
}useMemo is optional for a short list; add it when the list is large and say why.
Tips
- Mention localeCompare for text so accents and capitals sort sensibly.
Practise it yourself in the React and Angular code playground.
Learn this topic
React.js Full Course: Beginner to Advanced .
Sign in to add your own answer.
More questions
- Coding exercise: build a Todo application in React.
- Coding exercise: create a search box with debounce in React.
- Coding exercise: fetch API data and display it in a table in React.
- Coding exercise: implement pagination in React.
- Coding exercise: create a login form with validation in React.
- Coding exercise: build a parent-child communication example in React.