React 5 3 understand the keys
Open the running application in the browser and hit F12 to open the developer console. You will notice a warning printed by React mentioning a missing key prop on every list item. In this short lesson we fix this warning — it is actually trivial, but understanding why it exists is important.
Open Expenses.js (or wherever you call .map() on the expenses array) and locate the <ExpenseItem /> rendered inside the callback. We simply add an extra prop called key, taking the value of each expense's unique id.
{props.items.map((expense) => (
<ExpenseItem
key={expense.id}
title={expense.title}
amount={expense.amount}
date={expense.date}
/>
))}
Why React needs a key
- The
idvalues come fromApp.js— we already hade1,e2,e3ande4on each entry. - React uses the
keyto track which list item corresponds to which DOM node when the array changes. - Without a stable key, React falls back to the array index, which is unsafe when items are added, removed or reordered.
Save the file and reload the page. Open the console again: the warning has disappeared. The expense list still renders the same way, but React now has a reliable identifier per item, which keeps the rendering correct as we add, remove or reorder expenses. That's all there is to know about key for now.
Summary
This lesson explains how to resolve React's console warning about missing keys in list items. By adding a `key` prop to each element (using a unique identifier like `id`), you eliminate the warning and help React properly track component instances. The example shows adding `key={id}` inside the JSX curly braces, which immediately removes the console error.
Key points
- React displays a console warning when list items lack a `key` prop
- The `key` prop helps React identify which items have changed, been added, or removed
- Add the `key` attribute inside JSX curly braces: `key={id}`
- Use a unique identifier from your data (such as an `id` property) as the key value
- Once keys are properly added, the console warning disappears completely
FAQ
Why does React require keys for list items?
Keys help React identify which items have changed and maintain component state correctly. Without them, React may reuse component instances incorrectly, causing bugs and console warnings.
What should I use as a key value?
Use a unique identifier from your data, such as an `id` property. Avoid using array indices, as they can cause issues if the list order changes.
How do I add a key to JSX elements?
Add the `key` prop inside the JSX curly braces: `<div key={item.id}>...</div>`. The key value should be unique for each element in the list.