Applications display lists everywhere—from navigation links and notification feeds to shopping cart rows. In React, you transform arrays of data into arrays of JSX elements using JavaScript's .map() method, paired with a unique key prop on each returned item.
key Prop MattersReact uses key strings to match items across renders when rows are added, reordered, or deleted. Without stable keys, React cannot tell which row moved, so it may update the wrong DOM node or mix up input values between items.
export function InvoiceList({ invoices, onSelect }) {
if (invoices.length === 0) {
return <p>No invoices found.</p>;
}
return (
<ul className="invoice-list">
{invoices.map((invoice) => (
<li key={invoice.id} className="invoice-item">
<span>#{invoice.number} — ${invoice.total}</span>
<button type="button" onClick={() => onSelect(invoice.id)}>
View
</button>
</li>
))}
</ul>
);
}
key={user.id}, key={post.slug}) because IDs remain fixed even if the array is sorted or filtered.key={index}): Safe only when the list is static, never reordered, never filtered, and contains no stateful inputs.Math.random() or crypto.randomUUID() during render): Never generate keys inside .map(). A fresh key on every render forces React to destroy and rebuild every row from scratch.key on the Inner Element Instead of the Root: When .map() returns <ListItem key={item.id} />, put key directly on <ListItem>, not on the <li> inside ListItem.key trigger React console warnings and cause missing or duplicated rows during updates.props.key inside a child component?No. React strips key internally and does not pass it down as a prop. Pass a separate prop such as itemId={item.id} if the child needs the identifier.
Use the explicit <Fragment key={item.id}>...</Fragment> syntax, since the shorthand <>...</> cannot accept a key prop.
No. Keys only need to be unique among sibling elements inside the same array.
Sign in to track your learning journey, earn industry-recognized certificates, and join our elite developer community.
Quick Access With