1

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

1

2 Answers 2

2

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>
Sign up to request clarification or add additional context in comments.

Comments

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>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.