Reputation: 485
So, here I'm trying to map through a response I get from an API, before I get the items from the API, I was testing it statically and I made a unique number id for every item starting from {1} and now I'm trying find a way to make some kind of for loop for every item I get to give every item a unique number id starting from {1}, how can I achieve that?
<div className="items">
{this.state.items.map(i =><a href="/" id={1} onClick={this.targetValue} className={this.state.selected === "1" ? "selected" : ""}>{i.name}</a>
</div>
Upvotes: 1
Views: 266
Reputation: 34014
The .map gives you index and you can use that for unique id. Since you want id to start from 1 you need to to index+1 because index starts from 0
<div className="items">
{this.state.items.map((i, index) => <a href="/" id={index+1} onClick={this.targetValue} className={this.state.selected === index +1? "selected" : ""}>{i.name}. </a>
</div>
Upvotes: 1
Reputation: 10045
The map function actually gives you an index as a second parameter.
<div className="items">
{this.state.items.map((i, idx) =><a href="/" id={idx} onClick={this.targetValue} className={this.state.selected === "1" ? "selected" : ""}>{i.name}</a>
</div>
Upvotes: 1