How to Use Map() to Loop Over & Render an Array in React.js
In React.js, you can easily build collections of elements from an array of values and include them in your JSX using curly braces {}
.
The map()
method is one of the easiest ways to do this.
In the code below, we have a names
array. We loop over each item in the array and return an <li>
element for each one.
Then we include the whole listOfItems
array inside a <ul>
element and render it to the DOM.
render() {
const names = ["Bill", "Bob", "Bilbo", "Jeff"]
const listOfItems = names.map((name, index) =>
<li key={index}>{name}</li>
)
return (
<ul>{listOfItems}</ul>
)
}
Also, notice that each <li>
element is given a unique key
value based on its index position in the array. These help React identify which items have changed, have been added, or have been removed.
You can also add the map()
method directly inside the render()
function.
Check out the code example below:
render() {
const names = ["Bill", "Bob", "Bilbo", "Jeff"]
return (
<ul>
{names.map((name, index) => {
return <li key={index}>{name}</li>
})}
</ul>
)
}