How to Fix Each Child Should Have Unique Key in React
React shows the warning
each child should have a unique key when list items lack a unique key prop. To fix it, add a unique and stable key to each child element, usually using a unique id or index if no id is available.Why This Happens
React needs a unique key for each child in a list to track which items changed, added, or removed. Without unique keys, React can't update the UI efficiently and shows a warning.
jsx
import React from 'react'; function ItemList() { const items = ['apple', 'banana', 'cherry']; return ( <ul> {items.map(item => ( <li key={item}>{item}</li> // Added key prop here ))} </ul> ); } export default ItemList;
Output
Warning: Each child in a list should have a unique "key" prop.
The Fix
Add a unique key prop to each child element inside the list. Use a unique id if available or the index as a last resort. This helps React identify each element correctly.
jsx
import React from 'react'; function ItemList() { const items = ['apple', 'banana', 'cherry']; return ( <ul> {items.map((item, index) => ( <li key={index}>{item}</li> // Added unique key using index ))} </ul> ); } export default ItemList;
Output
<ul><li>apple</li><li>banana</li><li>cherry</li></ul> (No warnings)
Prevention
Always assign a unique and stable key prop when rendering lists. Prefer unique IDs from your data over array indexes to avoid bugs when list order changes. Use linting tools like eslint-plugin-react to catch missing keys early.
Related Errors
Other common React list errors include:
- Duplicate keys: Using the same key for multiple items causes rendering issues.
- Keys on wrong elements: Keys must be on the direct child elements inside the list.
Key Takeaways
Always provide a unique key prop to each list child in React.
Use stable unique IDs from your data instead of array indexes when possible.
Missing or duplicate keys cause React warnings and UI bugs.
Lint your code to catch missing keys early.
Keys help React update lists efficiently and correctly.