Coding exercise: implement sorting and filtering in React.

React practical coding · Freshers and experienced

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

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