Reputation: 1430
I have the following piece of jsx in my reactjs program,
<select onChange = {this.selectChange}>
<option>{this.state.array[0]}</option>
<option>{this.state.array[1]}</option>
<option>{this.state.array[2]}</option>
<option>{this.state.array[3]}</option>
</select>
Its actually much longer than this, I have 32 elements in the array so I'd like to find a more compact way of doing this. For example, I was thinking something like this:
<select onChange = {this.selectChange}>
{for (var n=0; n<32; n++) <option>{this.state.array[n]}</option>}
</select>
However that doesn't work. How might I do this? Thanks
Upvotes: 0
Views: 33
Reputation: 605
usually best to just use a map:
<select onChange = {this.selectChange}>
{this.state.array.map(item => (
<option>{item}</option>
))}
</select>
The reason the for loop version is not working is because jsx doesn't know how to parse a for loop correctly because it would have to connect 2 disparate jsx blocks (because of the squiggly bracket block that would need to be accounted for).
Upvotes: 1
Reputation: 12874
const options = this.state.array.map(op => {
return <option>{op}</option>
});
return (
<select onChange = {this.selectChange}>
{options}
</select>
);
To improve readability, you can separate them into another variable options
, then within that variable using a map function to generate individual item.
To answer your question, your way doesn't work is because there is missing return
key
Upvotes: 1