How to loop through an array of objects in React

Last updated on Aug 26, 2020 by Suraj Sharma



Looping through an array of objects in React is very common. One of the use case is to loop through the response objects array and create a component or a jsx element multiple times in React.


return (
  <div>
  <List key={1}>One</List>
  <List key={2}>Two</List>
  <List key={3}>Three</List>
  </div>
)

The above code snippet is a basic example of creating a jsx element multiple times in React. This can be done using a for loop or a array.map() method in React.

In this tutorial, I am going to cover multiple ways of looping through an array to create jsx elements in React.

Let’s create a MenuList Component using a function component, which will create multiple food items along with its price in a tabular form.


const MenuList = () => {
  const items = [
  {
    id: 1,
    name: 'Pizza',
    price: '$12.99'
  },
  {
    id: 2,
    name: 'Burger',
    price: '$9.99'
  },
  {
    id: 3,
    name: 'Taco',
    price: '$1.99'
  }
  ]
  return(<></>)
}

export default MenuList


Iterate through an array of objects in React


1. Using For Loop


for-of loop is not very common among React developers for iterating through an array of objects in React.

It requires you to iterate through the array and push the elements into a new array and then wrap the array by curly brace inside the return statement.


 const itemRows = [];
 for (let item of items) {
   const row = (
     <tr key={item.id}>
       <td key={1}>{item.id}</td>
       <td key={2}>{item.name}</td>
       <td key={3}>{item.price}</td>
     </tr>
   );
   itemRows.push(row);
 }
 return (
   <table>
     <thead>
       <tr>
         <th>#</th>
         <th>Name</th>
         <th>Price</th>
       </tr>
     </thead>
     <tbody>
       {itemRows}
     </tbody>
   </table>
 );
}


2. Using Array.map() method


The most commonly used method for iterating through an array in React.js.

It prevents you from declaring a new array. Array.map() method returns a new array of the jsx elements.


return (
   <table>
     <thead>
       <tr>
         <th>#</th>
         <th>Name</th>
         <th>Price</th>
       </tr>
     </thead>
     <tbody>
       {items.map(item=>(
         <tr key={item.id}>
           <td key={1}>{item.id}</td>
           <td key={2}>{item.name}</td>
           <td key={3}>{item.price}</td>
         </tr>
       ))}
     </tbody>
   </table>
 );


Related Solutions


Rate this post


Suraj Sharma is a Full Stack Software Engineer. He holds a B.Tech degree in Computer Science & Engineering from NIT Rourkela.