From an array to a list of elements
Almost any real interface shows collections: a list of tasks, the
results of a search, the comments on a post. In React there is no
special loop inside JSX: you use the .map() method of arrays to
transform each piece of data into a JSX element.
function ShoppingList() {
const products = ["Bread", "Milk", "Eggs"];
return (
<ul>
{products.map((product) => (
<li>{product}</li>
))}
</ul>
);
}
.map() returns a new array, this time of <li> elements, and React knows
how to paint an array of elements one after another. Notice that the .map() goes
inside curly braces { }: it is a JavaScript expression embedded in the JSX.
The key prop
If you run the code above, React will show a warning in the console:
Warning: Each child in a list should have a unique "key" prop.
Each element of a list needs a special prop called key: a
unique and stable identifier within that list.
<ul>
{products.map((product) => (
<li key={product}>{product}</li>
))}
</ul>
What is the key for?
The key helps React identify each element across renders. When
the list changes (an element is added, removed, or reordered), React compares the keys
to know which element is which and update only what is needed, instead of
recreating the whole list. This improves performance and avoids subtle bugs
(for example, the text of an <input> jumping to another row).
A good key:
- Is unique among the siblings of the same list (it does not have to be unique in the whole app).
- Is stable: the same data should always have the same key. The ideal is an
id that comes from your data (
task.id,user.id...).
What about the .map() index?
.map() gives you the index as a second argument:
{products.map((product, index) => (
<li key={index}>{product}</li>
))}
Using the index as key is tempting, but it is fragile: if the list is reordered, filtered, or elements are inserted/removed in the middle, the index of each piece of data changes, and React can confuse the rows. It is only acceptable when the list is static (does not change order or size) and you do not have a better id.