Module 32: Components and Props
Lists and keys
🏠The everyday picture
A teacher with a class register knows each student by roll number, not by where they sit. If students change seats, the teacher still knows who's who.
📘What it really is
- Show a list by mapping an array to components (Module 22's
map):
<ul className="enquiry-list">
{enquiries.map(enquiry => (
<li key={enquiry.id}>
<EnquiryCard enquiry={enquiry} />
</li>
))}
</ul>
-
Every item needs a
key: a value that's unique among its siblings and stable (the same item always has the same key). React uses keys to tell which items were added, removed or moved. -
Use an id from the data. Don't use the array index as a key when items can be added, removed or reordered: React mixes them up, and things like typed text or checkboxes appear on the wrong item.
-
Missing keys cause a warning in the console; fix every one.
- Filter and sort before mapping, never changing the original array (Module 22):
enquiries.filter(e => e.status !== "closed").toSorted(byNewest).map(...).
🖱️Try it
Render all sample enquiries with map and key={enquiry.id}. Show only open ones in the first panel and closed
ones in the second, newest first. Remove the key and read the warning; then put it back.
✅Quick check
Why not use the array index as a key in a list where items can be deleted?
Show the answer
Indexes shift when items are removed, so React matches the wrong items, causing display bugs.
What makes a good key?
Show the answer
A value that's unique among the list's items and stays the same for each item, usually its id.
