React
Beginner
2 min read
Rendering Lists with .map() and the key Prop
Example
// ── Basic list rendering ──────────────────────────────────────
const fruits = ['Apple', 'Banana', 'Cherry', 'Date'];
function FruitList() {
return (
<ul>
{fruits.map((fruit) => (
<li key={fruit}>{fruit}</li> // key = stable unique value
))}
</ul>
);
}
// ── List of objects with IDs ──────────────────────────────────
const users = [
{ id: 1, name: 'Alice', role: 'admin' },
{ id: 2, name: 'Bob', role: 'editor' },
{ id: 3, name: 'Charlie', role: 'viewer' },
];
function UserTable() {
return (
<table>
<thead>
<tr><th>Name</th><th>Role</th></tr>
</thead>
<tbody>
{users.map(user => (
<tr key={user.id}> {/* key on the outermost element */}
<td>{user.name}</td>
<td>{user.role}</td>
</tr>
))}
</tbody>
</table>
);
}
// ── Filter + map ──────────────────────────────────────────────
function AdminList() {
const admins = users.filter(u => u.role === 'admin');
if (admins.length === 0) return <p>No admins found.</p>;
return (
<ul>
{admins.map(u => <li key={u.id}>{u.name}</li>)}
</ul>
);
}
export default UserTable;