To render lists and handle keys in React, you can use the map
method to iterate through an array of data and returns a new array of React elements. Here's a basic example:
First, create an array of data:
const data = [
{ id: 1, item: 'Apple' },
{ id: 2, item: 'Banana' },
{ id: 3, item: 'Orange' }
];
Then, render the list using map
in your component:
function MyComponent() {
return (
<ul>
{data.map(item => (
<li key={item.id}>{item.item}</li>
))}
</ul>
);
}
In this example, we use the map
method to iterate through the data
array and return an array of <li>
elements with a unique key
prop based on the item
's id
. The key
prop is important for React to efficiently update the list when items are added, removed, or reordered.
Make sure to always provide a unique key for each item in a list to help React correctly identify each item and efficiently update the DOM.