Understanding the use of keys in React

87 views Asked by At

I have this simple example of list rendering in React:

  render() {
    return (
      <ul>
        {this.state.cards.map(({ data }, index) => (
          <li key={index} onClick={() => this.remove(index)}>
            {data}
          </li>
        ))}
      </ul>
    );
  }

  remove = index => {
    let cards = this.state.cards.filter((card, i) => i != index);
    this.setState({ cards });
  };

Here I use the index as key and there is something I don't understand even after searching keys in React in google and reading the manual:

The remove function changes the indices which in turn changes the keys of some elements in the list (so if I removed number 2 all the keys of the elements afters it changes).

So I'd actually expect this function to always remove the last item in the list, since only this key is removed each time, but surprisingly or not it works the way it "should" and removes the right element each time -- when I look at the React console in Chrome I see it changes keys but doesn't delete and create again those elements which had their keys changed...

I am very confused about what's happening here ((⇀‸↼))

0

There are 0 answers