How to Run Foreach Loop in React

Published on July 24, 2020 56 sec read

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

  1. Basic Example
  2. Loop with Index
  3. Multidimensional Array

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. 🙂

Monthly Newsletter

One email a month, packed with the latest tutorials, delivered straight to your inbox.
We'll never send any spam or promotional emails.
Author

Hey, I'm Md Obydullah. I build open-source projects and write on Laravel, Linux server, modern JavaScript and more on web development. If you enjoy my content, please consider supporting what I do!

Follow Buy me a coffeeBuy me a coffee

Leave a Reply

Your email address will not be published. Required fields are marked *