Turn an array of data into a list of on-screen elements with map, and identify each element with keys.
Open this lesson in KodokonInterfaces 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.
const fruits = ["apple", "banana", "kiwi"];
const upperFruits = fruits.map(function (fruit) {
return fruit.toUpperCase();
});
console.log(upperFruits);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.
function FruitList() {
const fruits = ["apple", "banana", "kiwi"];
return (
<ul>
{fruits.map((fruit) => (
<li key={fruit}>{fruit}</li>
))}
</ul>
);
}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.
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>
);
}key prop for?