A
key
is a special string attribute that you must
include when creating arrays of elements. Keys help React determine which items have been changed, added or removed.
Most often we use identifiers from our data as keys :
const todoItems = todos.map((todo) =>
<li key={todo.id}>
{todo.text}
</li>
)
If you don't have stable identifiers for the items being rendered, you can use the item's index as the key as a last resort:
const todoItems = todos . map (( todo , index ) => < li key = { index } > { todo . text } </ li > )
Notes:
- Using indexes for keys is not recommended if the order of the items may change. It can hurt performance and may cause problems with component state.
- If you extract a list item as a separate component, then apply the keys to the list component instead of the
li
tag.
- A warning message will appear in the console if the
key
prop is missing from list items.
Comments