reactjsreact-data-grid

Loop through array using Map in React throw error


I have a functional component which is reading data from an API. I have defined an Interface but unable to loop and display in table using Map in react.

error

index.js:1 Warning: Each child in a list should have a unique "key" prop.

Interface

export interface ISiteManager{
   managerId: number,
   name: string,
   isDeleted: false
}

React functional component return template

...
return (
  
<div>
  <h2>EziTracker Dashboard Report</h2>
    {eziStatusCollection && eziStatusCollection.length >0 && (
    <table  className="table">
      <thead>
        <tr>
          <th>ManagerId</th>
          <th>Name</th>
          <th>Is Deleted</th>
        </tr>
      </thead>
      {
        eziStatusCollection.map((item, index) => {
          return(
          <tbody>
            <tr key={index}>
              <td>{item.managerId}</td>
              <td>{item.name}</td>
              <td>{item.isDeleted}</td>
            </tr>
          </tbody>
        )})
      }
    </table>)}
  </div>
 );
};

export default MyComponent;

Solution

  • Your table body should be outside the map, as it's looping it each time as well:

    <tbody>
         {
            eziStatusCollection.map((item, index) => {
              return(
              
                <tr key={index}>
                  <td>{item.managerId}</td>
                  <td>{item.name}</td>
                  <td>{item.isDeleted}</td>
                </tr>
            )})
          }
      </tbody>
    

    This way the map key will be associated with each child (tr) and the error shouldn't occur.