Kodokon kodokon.com

Rendering lists and the role of keys

Turn an array of data into a list of on-screen elements with map, and identify each element with keys.

8 min · 3 questions

Open this lesson in Kodokon

Interfaces are full of lists: messages in a conversation, products in a store, tracks in a playlist... Instead of copy-pasting tags by hand, you start from an array of data and transform it with the map method. Quick reminder: map applies a function to every element of an array and returns a new array with the results.

JAVASCRIPT
const fruits = ["apple", "banana", "kiwi"];

const upperFruits = fruits.map(function (fruit) {
  return fruit.toUpperCase();
});

console.log(upperFruits);
map turns each fruit into uppercase

In React, you do exactly the same, except the function passed to map returns JSX instead of a string. React knows how to display an array of JSX elements: it renders them one after the other. The only requirement is to give each element a special prop named key.

JSX
function FruitList() {
  const fruits = ["apple", "banana", "kiwi"];

  return (
    <ul>
      {fruits.map((fruit) => (
        <li key={fruit}>{fruit}</li>
      ))}
    </ul>
  );
}
Each list item gets a unique key

What is key for? It's a unique label that lets React recognize each element when the list changes (adding, removing, reordering), like the numbered tickets at a coat check: without a number, there is no way to return the right coat. Thanks to keys, React only updates what has actually changed. In practice, the best key is a unique, stable identifier coming from your data, such as an id field.

JSX
const tasks = [
  { id: 1, label: "Buy groceries" },
  { id: 2, label: "Water the plants" },
];

function TaskList() {
  return (
    <ul>
      {tasks.map((task) => (
        <li key={task.id}>{task.label}</li>
      ))}
    </ul>
  );
}
Each task's id serves as a stable key

Knowledge check

Make sure you remember the key points of this lesson.

  1. Which array method do you use to render a list in React?
    • push
    • map
    • forEach
  2. What is the key prop for?
    • Automatically sorting the list alphabetically
    • Protecting the list with a password
    • Letting React identify each element of the list
  3. What is the best value for a key?
    • A unique, stable identifier coming from the data
    • The element's index in the array, in every case
    • A random number generated on every render