Loop in JSX with Map Function

What is an Array?

An array is a collection of data. If you have one name, you store it in a variable. But if you have many names, use an array.


Example:

const userData = ["Anil", "Sam", "Peter", "Bruce"];
const collegeData = ["IET", "IIT", "NIT"];


Array of Objects

When each user has more details like name, age, email, use array of objects.

const userData = [
{
name: "Anil",
age: 29,
email: "anil@test.com",
id: 1,
},
{
name: "Sam",
age: 36,
email: "sam@test.com",
id: 2,
},
{
name: "Peter",
age: 20,
email: "peter@test.com",
id: 3,
},
{
name: "Bruce",
age: 50,
email: "bruce@test.com",
id: 4,
},
];


Make Table in JSX

Create a table structure like this:

<h1>Dummy Data</h1>

<table border="1">
<thead>
<tr>
<td>Id</td>
<td>Name</td>
<td>Email</td>
<td>Age</td>
</tr>
</thead>
<tbody>
<tr>
<td>1</td>
<td>Anil</td>
<td>anil@test.com</td>
<td>29</td>
</tr>
{/* More rows... */}
</tbody>
</table>

But instead of repeating rows manually, use .map().


Use map() Function for Looping

<div>
<h1>Loop in JSX with Map Function</h1>

<table border="1">
<thead>
<tr>
<td>Id</td>
<td>Name</td>
<td>Email</td>
<td>Age</td>
</tr>
</thead>
<tbody>
{userData.map((user) => {
return (
<tr key={user.id}> {/* key helps React track each row */}
<td>{user.id}</td>
<td>{user.name}</td>
<td>{user.email}</td>
<td>{user.age}</td>
</tr>
);
})}
</tbody>
</table>
</div>


  1. map() runs a loop on the array.
  2. It returns one <tr> for each user.
  3. key={user.id} gives a unique identity to each row.