adding key to map function is not working

Viewed 69

I am currently trying to add a key to my map. However, when I try and give it an index, it then shows up with persons as undefined. Where it was working before. Here is what I have done.

   <div className='UserAdminCardsGrid'>
          {personValues.map(person, index =>
            <div key={index} className="UserAdminCard Card">
              <b>Name:</b>
              <div>{person.name}</div>
              <b>ID:</b>
              <div>{person.id}</div>
            </div>
          )}
        </div>
4 Answers

It is a wrong syntaxis

personValues.map(person, index =>

Wrap arguments in parentheses

personValues.map((person, index) =>

Add parenthesis in the arrow function:

  <div className='UserAdminCardsGrid'>
       personValues.map((person, index) =>
            <div key={index} className="UserAdminCard Card">
              <b>Name:</b>
              <div>{person.name}</div>
              <b>ID:</b>
              <div>{person.id}</div>
            </div>
       )}
   </div>

Wrap your argument in parenthesis or use object id

wrapping and using map function index

personValues.map((person, index) =>

or use object id as a key (Recommended to use)

{personValues.map(person =>
  <div key={person.id} className="UserAdminCard Card">
   <b>Name:</b>
   <div>{person.name}</div>
   <b>ID:</b>
   <div>{person.id}</div>
   </div>
 )}

Index as a key is an anti-pattern

It may break your application and display the wrong data!

refer to Index as a key is an anti-pattern article for better understanding.

 <div className='UserAdminCardsGrid'>
          {personValues.map(({id, name}) =>
            <div key={id} className="UserAdminCard Card">
              <b>Name:</b>
              <div>{name}</div>
              <b>ID:</b>
              <div>{id}</div>
            </div>
         )}
  </div>
Related