In React, lists are created from arrays using JavaScript’s map() function. Each rendered item must include a unique key so React can efficiently update only the elements that change instead of re-rendering the entire list.
map().key.The map() method transforms an array into JSX elements. React uses the key attribute to detect which items are added, removed, or updated.
// Rendering a list of strings using map()
function NameList() {
const names = ["Alice", "Bob", "Charlie"];
return (
<ul>
{names.map((name) => (
<li key={name}>{name}</li>
))}
</ul>
);
}
// Always provide a unique key when rendering items
{items.map((item) => <li key={item.id}>{item.name}</li>)}
// Rendering list from array of objects
function ProductList() {
const products = [
{ id: 1, name: "Laptop", price: 60000 },
{ id: 2, name: "Phone", price: 25000 },
{ id: 3, name: "Tablet", price: 30000 }
];
return (
<ul>
{products.map((p) => (
<li key={p.id}>{p.name} — ₹{p.price}</li>
))}
</ul>
);
}
// Rendering components dynamically
function Product({ name, price }) {
return <li>{name} — ₹{price}</li>;
}
function ProductList() {
const items = [
{ id: 1, name: "Keyboard", price: 1500 },
{ id: 2, name: "Mouse", price: 800 },
{ id: 3, name: "Monitor", price: 12000 }
];
return (
<ul>
{items.map((item) => (
<Product key={item.id} name={item.name} price={item.price} />
))}
</ul>
);
}
// Using index as key (not recommended for dynamic lists)
{items.map((item, index) => (
<li key={index}>{item}</li>
))}
React uses key values internally to determine what has changed in a list. Stable keys allow DOM updates to be faster and prevent unexpected UI behavior when items are added, removed, or reordered.
key values.Goal: Master rendering dynamic lists using map() and optimize UI updates with proper keys.