Ad

React - Iterate Counter For Each Component

- 1 answer

This, like every thing, is probably painfully simple. I'm having trouble iterating a count (1, 2, 3, 4, etc up to 50) that I'm passing props to a component:

const cards = []

const counter = 0

someData.map(() => {
  cards.push(<SomeCard count1={counter} count2={counter + 1} />)
})

It should come out representing something like this (iterating up to 50):

<SomeCard count1="0" count2="1" />
<SomeCard count1="1" count2="2" />
<SomeCard count1="2" count2="3" />
<SomeCard count1="3" count2="4" />
<SomeCard count1="4" count2="5" />

IE I'd like to iterate "SomeCard" 50 times with "count1" and "count2" climbing in sequence each time. Any help is thoroughly appreciated!

Ad

Answer

Use the index in the map callback instead - and don't use .push, .map is for creating a new array from scratch, not for side-effects.

const cards = someData.map((_, i) =>
  <SomeCard count1={i} count2={i + 1} />
)

Passing two props when one's data can be completely determined from the other is superfluous though - consider leaving off count2 entirely, and calculating it inside SomeCard.

Ad
source: stackoverflow.com
Ad