Chapter 1 of 4

Rendering Lists

Turning arrays of data into arrays of elements.

React renders arrays by rendering each item in order, so the usual way to display a collection is map.

function ProductList({ products }) {
  return (
    <ul>
      {products.map((product) => (
        <li key={product.id}>
          {product.name} - {product.price}
        </li>
      ))}
    </ul>
  );
}

Filtering and sorting

Chain array methods before mapping. Copy before sorting, because sort mutates the array it is called on.

const visible = products
  .filter((product) => product.inStock)
  .sort((a, b) => a.price - b.price);   // safe: filter already made a copy

// If you did not filter first, copy explicitly
const sorted = [...products].sort((a, b) => a.price - b.price);

Empty states

An empty array renders nothing at all, which usually looks like a broken page. Handle it explicitly.

function ProductList({ products }) {
  if (products.length === 0) {
    return <p>No products match your filters.</p>;
  }

  return <ul>{products.map(/* ... */)}</ul>;
}