π Rendering Lists in React
In React, rendering lists is a common task β whether it's showing users, products, or posts. The .map() method is your go-to tool.
1οΈβ£ Rendering with .map()
const names = ["Alice", "Bob", "Charlie"];
function NameList() {
return (
<ul>
{names.map((name) => (
<li>{name}</li>
))}
</ul>
);
}
2οΈβ£ Adding key Props
Keys help React identify which items changed, are added, or removed:
const users = [
{ id: 1, name: "Alice" },
{ id: 2, name: "Bob" },
];
function UserList() {
return (
<ul>
{users.map((user) => (
<li key={user.id}>{user.name}</li>
))}
</ul>
);
}
3οΈβ£ Conditional List Rendering
function ProductList({ products }) {
if (products.length === 0) {
return <p>No products found.</p>;
}
return (
<ul>
{products.map((item) => (
<li key={item.id}>{item.name}</li>
))}
</ul>
);
}
β Best Practices
- Use unique keys (not array index unless necessary)
- Extract list items into components for clarity
- Use fragments if you donβt need a wrapper element