The easiest way to loop over an array in React JSX is by using the native map function:
const users = [
{
id: 1,
name: 'John Doe',
},
{
id: 2,
name: 'Jack Rolsten',
},
]
function UsersList() {
return (
<ul>
{users.map((user) => (
<li key={user.id}>{user.name}</li>
))}
</ul>
)
}
Note: You might have noticed that each <li>
element contains a key
prop. Keys help React identify which items have changed, are added, or are removed. Keys should be given to the elements inside the array to give the elements a stable identity:
Create a JSX fragment with a for each loop
function FruitsList(props) {
const fruits = [🍎,🍌,🥭,🍐];
const listOfFruits = [];
fruits.forEach((fruit, index) => {
listOfFruits.push(<li key={index}>{fruit}</li>)
})
return (
<ul>
{listOfFruits}
</ul>
)
}