Careeroza
Rendering Lists and Keys
map() and key
Example
Use map() to turn an array into elements. Each item needs a unique, stable key so React can track it between renders.
const courses = [
{ id: 1, name: 'HTML', hours: 10 },
{ id: 2, name: 'CSS', hours: 14 },
{ id: 3, name: 'React', hours: 30 },
];
export default function App() {
return (
<ul>
{courses.map((c) => (
<li key={c.id}>{c.name} — {c.hours} hours</li>
))}
</ul>
);
}Result
Why Not Use the Index as Key?
If items can be added, removed or re-ordered, an index key makes React reuse the wrong element: input values and state jump to another row. Use an id from your data. The index is only OK for static lists that never change.