1. Rendering Lists with the map() Function
In React, collections of items are transformed into arrays of JSX elements using standard JavaScript array methods, predominantly .map().
function SubjectList() {
const subjects = ["Physics", "Chemistry", "Mathematics", "Biology"];
return (
{subjects.map(subject => (
- {subject}
))}
);
}
2. The Crucial Role of the key Prop
When rendering lists, React requires each item to have a unique key prop. Keys give elements a stable identity across renders. When an item in an array is inserted, reordered, or deleted, React uses keys to determine which exact DOM nodes need updating rather than tearing down and rebuilding the whole list.
function QuestionPalette({ questions, onSelectQuestion }) {
return (
{questions.map(q => (
))}
);
}
3. Why You Should NOT Use Array Index as key
| Identifier Type | Safety | Behavior on Insertion / Deletion |
|---|---|---|
Unique Database ID (item.id) |
✅ Safe & Recommended | Items retain their identity, component state and input values remain properly aligned. |
Array Index (key={index}) |
❌ Dangerous anti-pattern | If items are deleted or filtered, indices shift. Form inputs, animations, and checkboxes can associate with the wrong item! |