Middle
When rendering a list in React, what property must be given to each element? Where can and where cannot keys be taken from?
sobes.tech AI
Answer from AI
When rendering a list in React, each element must have a key property. This helps React efficiently update and re-render only the changed list items.
Where to get keys:
- It's best to use unique and stable identifiers from your data, such as an
idfrom a database. - You can also use unique strings or numbers that do not change between renders.
What to avoid:
- Avoid using the array index as a key, especially if the order of items can change, as this may lead to incorrect component updates.
Example:
const items = [{id: 'a1', name: 'Item 1'}, {id: 'b2', name: 'Item 2'}];
return (
<ul>
{items.map(item => (
<li key={item.id}>{item.name}</li>
))}
</ul>
);