Search code examples
reactjsecmascript-6lodashfetch-api

make a unique number id for every item I get from the api response


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>

Solution

  • 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>