In this article, we’re going to see how to Iterate with foreach loop. We’ll do for or foreach loop with Map function (introduced in ES6). Let’s see a few examples:
Table of Contents
Basic Example
The most used method of iterating over an array in React is Map function. This is the basic example of Map:
App.js
import React from 'react';
const names = ['Name 1', 'Name 2', 'Name 3', 'Name 4', 'Name 5'];
function App() {
return (
<ul>
{names.map(name => (
<li>
{name}
</li>
))}
</ul>
);
}
export default App;
Loop with Index
We can get index number of array using Map:
<ul>
{names.map((name, index) => (
<li>
{index} - {name}
</li>
))}
</ul>
Multidimensional Array
Let’s run loop in a multidimensional array:
App.js
import React from 'react';
const students = [
{
'id': 1,
'name': 'Student 1',
'email': '[email protected]'
},
{
'id': 2,
'name': 'Student 2',
'email': '[email protected]'
},
{
'id': 2,
'name': 'Student 3',
'email': '[email protected]'
},
];
function App() {
return (
<div>
<table className="table table-bordered">
<tr>
<th>ID</th>
<th>Name</th>
<th>Email</th>
</tr>
{students.map((student, index) => (
<tr data-index={index}>
<td>{student.id}</td>
<td>{student.name}</td>
<td>{student.email}</td>
</tr>
))}
</table>
</div>
);
}
export default App;
That’s it. Thanks for reading. 🙂