Lists and Keys

In React, you can build collections of elements and include them in JSX by using the map() function to iterate over an array.

Rendering a List

You can loop through the numbers array and return an <li> element for each item.

JavaScript

const numbers = [1, 2, 3, 4, 5];
const listItems = numbers.map((number) =>
  <li>{number}</li>
);

The Importance of Keys

Keys help React identify which items have changed, been added, or been removed. They should be given to the elements inside the array to give the elements a stable identity.

JavaScript

const todoItems = todos.map((todo) =>
  <li key={todo.id}>
    {todo.text}
  </li>
);

Key Best Practices

Note: React will warn you in the console if you forget to include a key for items in a list.