How to Run Foreach Loop in React

Basic Example

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

<ul>
  {names.map((name, index) => (
    <li>
      {index} - {name}
    </li>
  ))}
</ul>

Multidimensional Array

import React from 'react';

const students = [
  {
    'id': 1,
    'name': 'Student 1',
    'email': 'student1@mnp.com'
  },
  {
    'id': 2,
    'name': 'Student 2',
    'email': 'student2@mnp.com'
  },
  {
    'id': 2,
    'name': 'Student 3',
    'email': 'student3@mnp.com'
  },
];

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;

Leave a comment

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