0

I'm starting to ReactJs and have a doubt when generating a list with an ordering. How do I include a counter inside my map?

The way I'm doing it is repeating the number 1 in all records. I wanted each record to have a counter (1 Adam, 2 Andrew, 3 Sophia ...)

<div>
  {
    data.contacts.data.map((contact) => {
      return (
        <div>
          <span>1</span>  <b>{contact.data.name} {contact.data.email}</b>
        </div>
      )
    })
  }
</div>

enter image description here

Gregory
  • 105
  • 4

2 Answers2

1

Use the second argument (array index) of the map method:

<div>
  {
    data.contacts.data.map((contact, index) => (
        <div>
          <span>{index + 1}</span>  <b>{contact.data.name} {contact.data.email}</b>
        </div>
      ))
  }
</div>
r.delic
  • 795
  • 7
  • 18
1

With map you have access to the index. So you can use the index to add a counter. Also, remember to add a key-value to each child you're printing with map (you can use the index for this).

<div>
  {
    data.contacts.data.map((contact, index) => {
      return (
        <div key={index}>
          <span>{index + 1}</span>  <b>{contact.data.name} {contact.data.email}</b>
        </div>
      )
    })
  }
</div>
rubenf01
  • 134
  • 1
  • 8