You are viewing a free preview of this lesson.
Subscribe to unlock all 10 lessons in this course and every other course on LearningBro.
Displaying collections of items is one of the most common tasks in any UI. React makes this straightforward using JavaScript's Array.map() method to transform data arrays into arrays of JSX elements.
function FruitList() {
const fruits = ["Apple", "Banana", "Cherry"];
return (
<ul>
{fruits.map((fruit) => (
<li>{fruit}</li>
))}
</ul>
);
}
This works, but React will warn you: Each child in a list should have a unique "key" prop.
When React renders a list, it needs a way to identify which items have changed, been added, or been removed between renders. Without keys, React has no choice but to re-render the entire list on every update. With keys, it can reconcile individual items efficiently.
Keys must be:
function TodoList({ todos }) {
return (
<ul>
{todos.map((todo) => (
<li key={todo.id}>{todo.text}</li>
))}
</ul>
);
}
The best keys are stable IDs from your data (database IDs, UUIDs). Avoid using the array index as a key when the list can be reordered or filtered — this leads to subtle bugs where React associates the wrong element with the wrong key.
Using the array index as a key is acceptable if all three conditions are true:
{staticItems.map((item, index) => (
<li key={index}>{item}</li>
))}
Keys should be placed on the outermost element returned from the map, even when that element is a custom component:
function ProductGrid({ products }) {
return (
<div className="grid">
{products.map((product) => (
<ProductCard key={product.id} product={product} />
))}
</div>
);
}
The ProductCard component itself does not receive key as a prop — keys are used internally by React and are not accessible inside the component.
You can chain filter and map to render only matching items:
function ActiveTodos({ todos }) {
return (
<ul>
{todos
.filter((todo) => !todo.done)
.map((todo) => (
<li key={todo.id}>{todo.text}</li>
))}
</ul>
);
}
Subscribe to continue reading
Get full access to this lesson and all 10 lessons in this course.