0

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 ((⇀‸↼))

Gabriele Petrioli
  • 191,379
  • 34
  • 261
  • 317
  • You define the onClick handler within the map function, so `index` is locally scoped and will be a unique `index` for each element. The keys don't have anything to do with what happens within the remove function. sidenote: using your a iterator as key is not recommended, since React uses these keys to optimize rendering. You should try not to change keys unless necessary. – Luuuud Mar 26 '20 at 11:36
  • Can you please elaborate more - I know that map scopes things and thus the remove function would have the right index when called. But after removing element from the list by updating the states all the keys of elements after it should be changed and therefore created again? This is the point I am not getting. – Ohad Shemesh Mar 26 '20 at 11:55
  • If I understand correctly the correct list item gets removed from the dom, and when you inspect via React Dev Tools, all `
  • ` elements still have the same key as before? My guess is that that shouldn't happen, but I'm not 100% sure. Maybe you can find some more info here? https://reactjs.org/docs/reconciliation.html – Luuuud Mar 26 '20 at 12:19
  • The keys are changing but the elements don't get removed from the dom and created again. – Ohad Shemesh Mar 26 '20 at 12:25
  • if the key is changed, the component was _rendered_ again. Rendering doesn't necessarily mean that the DOM element changes, that's up to the diffing algorithm. In the link I posted above there's more info on how this works. – Luuuud Mar 26 '20 at 12:28
  • Ok I thought changing the key means => removing the element from the dom. I'll read it hope it'll riddle me things out. thanks. – Ohad Shemesh Mar 26 '20 at 14:16