Search code examples
reactjskey

React: How to assign key based on state counter and increment state counter in mapping?


I'm building a react App that displays a list of items (the component name is 'el'). I would like each item to contain a unique key that is simply a counter (called 'rank' here) that the app increments for each item. I'm currently successfully assigning rank as the key in the mapping, but I don't know how to make to increment it so it's unique for each one. Is this possible? Should I use a for loop of some sort instead of map()?

class App extends Component {
  constructor() {
    super();
    this.state = {
      someList:[/*Some List of Elements*/],
      rank:0,
    };
  }
  render() {
    const {myList, rank} = this.state;
    return (
      <section>
        <div className="container-fluid">
          <div className="row mb-5">
            <div className="col">
              <ul className="list-group" id="list">
                {myList.map(
                  (el) => <AListElement id={el.id} text={el.text} key={rank}/>
                )}
              </ul>
            </div>
          </div>
        </div>
      </section>
  }


Solution

  • The map() function comes with a unique index counter parameter for each item:

    {myList.map(
      (el, index) => <AListElement id={el.id} text={el.text} key={index}/>
    )}