Gregory
Gregory

Reputation: 115

Insert counter in a reactjs map

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

Upvotes: 1

Views: 2558

Answers (2)

rubenf01
rubenf01

Reputation: 134

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>

Upvotes: 1

r.delic
r.delic

Reputation: 863

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>

Upvotes: 2

Related Questions