Lists and Keys
In React, you can build collections of elements and include them in JSX by using the map() function to iterate over an array.
Rendering a List
You can loop through the numbers array and return an <li> element for each item.
JavaScript
const numbers = [1, 2, 3, 4, 5];
const listItems = numbers.map((number) =>
<li>{number}</li>
); The Importance of Keys
Keys help React identify which items have changed, been added, or been removed. They should be given to the elements inside the array to give the elements a stable identity.
JavaScript
const todoItems = todos.map((todo) =>
<li key={todo.id}>
{todo.text}
</li>
); Key Best Practices
- Use unique IDs from your data as keys (e.g., from a database).
- Avoid using indexes as keys if the order of items may change, as this can negatively impact performance and cause issues with component state.
- Keys must be unique among siblings, but they don't need to be globally unique.
Note: React will warn you in the console if you forget to include a key for items in a list.