React Foundations · Rendering & JSX

Lists with map and key

Lists with map and key

A list in your data is a list on the page: names, scores, search results. You could hand-write one element per item, but the moment the data changes the markup is wrong. You want the elements to follow the array.

To render a list you turn an array of data into an array of JSX elements. The map method is the tool for the job: it produces one element per item.

const items = ['a', 'b', 'c'];

return (
  <ul>
    {items.map((item) => (
      <li key={item}>{item}</li>
    ))}
  </ul>
);

React renders the array of elements in order. Each element needs a key — a string that is unique among its siblings and stable across renders. React uses the key to match elements between renders, so it can tell which items were added, removed, or moved.

Use a value that identifies the item, such as its id or, for a list of unique strings, the string itself. Avoid the array index as a key when the list can reorder, because the index changes and React loses track of which element is which.

Your job is to render one list item per entry in a prop.

Challenge

A list is hard-coded to a single row, so it cannot show the items it is given. Export an App component from App.jsx that accepts an items prop — an array of strings — and renders an unordered list with one <li> per item.

The Test renders <App items={['a', 'b', 'c']} /> and counts the list items. The starter hard-codes a single item, so the Test fails — map over items and give each element a key.

App.jsx
export function App() {
  return (
    <ul>
      <li>a</li>
    </ul>
  );
}

No test run yet

The Test is hidden. Run it to check the Challenge — you only see the result, never the test source.