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!
CodePudding user response:
First off, counter should not be a constant. (use let
)
Secondly, you need to increment you counter variable. The current configuration does not alter the value of counter so it remains the same.
counter 1
returns a value to count2
without changing the value of counter!
So basically you need to assign the value to counter before you assign to count2
counter = counter 1
A shorthand for this is counter
which you assign directly to count2.
So overall, something like this:
const cards = []
let counter = 0
someData.map(() => {
cards.push(<SomeCard count1={counter} count2={ counter} />)
})
CodePudding user response:
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
.