Rendering Lists
You will often need to display multiple similar items from an array. The standard way to do this in React is with the JavaScript .map() method.
Basic List Rendering
const fruits = ["Apple", "Banana", "Cherry", "Date", "Elderberry"];
function FruitList() {
return (
<ul>
{fruits.map(fruit => (
<li key={fruit}>{fruit}</li>
))}
</ul>
);
}
The key Prop
Every list item must have a unique key prop. React uses keys to identify which items changed, were added, or were removed. Without keys, React re-renders the entire list on every change.
const users = [
{ id: "u1", name: "Alice", email: "alice@example.com", role: "Admin" },
{ id: "u2", name: "Bob", email: "bob@example.com", role: "User" },
{ id: "u3", name: "Carol", email: "carol@example.com", role: "User" },
];
function UserTable() {
return (
<table>
<thead>
<tr><th>Name</th><th>Email</th><th>Role</th></tr>
</thead>
<tbody>
{users.map(user => (
<tr key={user.id}> {/* โ Use stable ID as key */}
<td>{user.name}</td>
<td>{user.email}</td>
<td>{user.role}</td>
</tr>
))}
</tbody>
</table>
);
}
WarningNever use array index as a key for dynamic lists (lists that can be reordered, filtered, or have items added/removed). Index keys cause subtle bugs with component state. Always use a stable, unique identifier like
user.id.Filtering Lists
function TaskList({ tasks }) {
const activeTasks = tasks.filter(task => !task.done);
return (
<div>
<h2>Active Tasks ({activeTasks.length})</h2>
{activeTasks.length === 0 && <p>All done! ๐</p>}
<ul>
{activeTasks.map(task => (
<li key={task.id}>{task.title}</li>
))}
</ul>
</div>
);
}
Sorting Lists
function SortedProducts({ products }) {
// Sort returns a new array โ do NOT sort the original prop
const sorted = [...products].sort((a, b) => a.price - b.price);
return (
<ul>
{sorted.map(p => (
<li key={p.id}>{p.name} โ ${p.price}</li>
))}
</ul>
);
}