In React, rendering a list of items is a very common task β and doing it right helps performance and avoids rendering bugs. The secret ingredient? .map()
and the key
prop.
Lists appear everywhere:
Rendering them dynamically keeps your UI flexible and data-driven.
.map()
to Render ListsReact doesnβt have a built-in loop like for
.
Instead, use .map()
to transform an array into JSX elements.
const fruits = ['π Apple', 'π Banana', 'π Orange'];
function FruitList() {
return (
<ul>
{fruits.map((fruit) => (
<li>{fruit}</li>
))}
</ul>
);
}
πΈ Problem: React will warn you that each child needs a unique
key
prop.
key
Prop?The key
is a special prop React uses to identify which items in a list have changed, been added, or removed.
<ul>
{fruits.map((fruit, index) => (
<li key={index}>{fruit}</li>
))}
</ul>
id
)index
if the list might change or reorderconst users = [
{ id: 1, name: 'Alice' },
{ id: 2, name: 'Bob' }
];
function UserList() {
return (
<ul>
{users.map((user) => (
<li key={user.id}>{user.name}</li>
))}
</ul>
);
}
β
Each item has a unique key
β no warning
β
React can re-render efficiently when data changes
key
prop β React shows a warningindex
as key in lists that reorder β buggy UIDo This | Avoid This |
---|---|
Use .map() to render lists |
Using for loops in JSX |
Provide a unique key prop |
Omitting the key |
Use stable IDs if possible | Using Math.random() as key |
Keep list rendering pure | Mutating arrays during render |
{
items.length === 0 ? (
<p>No items found.</p>
) : (
<ul>
{items.map((item) => (
<li key={item.id}>{item.name}</li>
))}
</ul>
);
}
Concept | Description |
---|---|
.map() |
Used to loop through arrays and render JSX |
key |
Helps React identify items in a list |
Good Keys | Unique, stable values like IDs |
Avoid Index | Donβt use index as key in dynamic lists |