Reputation: 163
I am trying to render a repeating block in JSX using a for
loop, and this is how I went about it.
In my component, but outside my render, I have my function as follows:
tenCards = () => {
let block = [];
/* Outer loop for container */
for(var i = 0; i < 11; i+2){
block.push(
<div className="container">
<Card id={i}/>
<Card id={i+1}/>
</div>
);
}
return block;
}
And inside my render I am simple calling {this.tenCards()}
. I was getting a syntax error, and now it compiles successfully, but the page never loads, and I get the
aw snap chrome error.
Am I just doing the for loop wrong?
After switching i+2 with i+=2 it does move one step forward, but JSX says property values have to be expressions or text, so the id={i} is not working and putting quotes around it makes it a string and for some reason I can't escape the quotes with \
.
I fixed the property error that it needs to be a string like this
<Card id={`${i}`} />
So that way JSX knew it was a JavaScript expression that gave a number between 0 & 10 and later `` quotes were placed around the number to make it a string. If you know a simpler way to do it please comment, but this is what worked for me.
Upvotes: 0
Views: 323
Reputation: 163
I fixed the property error that needs to be a string like this:
<Card id={`${i}`} />
So that way JSX knew it was a JavaScript expression that gave a number between 0 & 10 and later `` quotes were placed around the number to make it a string. If you know a simpler way to do it please comment, but this is what worked for me.
Upvotes: 1
Reputation: 96
You could try something like this:
const numbers = [2, 4, 6, 8, 10];
const cards = numbers.map((i) =>
<div className="container">
<Card id={i}/>
<Card id={i+1}/>
</div>
);
More info: https://reactjs.org/docs/lists-and-keys.html#rendering-multiple-components
Upvotes: 1