JavaScript

Sharina Jones
Sharina Jones
17,782 Points

Why do we need to use the index? Why can't we use the key?

In the video React Components / Managing State and Data Flow/ Update State Based on a Player's Index, why do we need to include the index? Isn't the purpose of the key to ensure that React can recognize each individual player? Why can't we use the key instead of creating a separate index?

render() {
    return (
      <div className="scoreboard">
        <Header title="Scoreboard" totalPlayers={this.state.players.length} />

        {/* Players list */}
        {this.state.players.map((player, index) => (
          <Player
            name={player.name}
            score={player.score}
            id={player.id}
            key={player.id.toString()}
            index={index}
            changeScore={this.handleScoreChange}
            removePlayer={this.handleRemovePlayer}
          />
        ))}
      </div>
    );

1 Answer

Pierson Brannan
Pierson Brannan
989 Points

Huh, that's weird. I have two answers for the instances of what you question might be, along with a follow-up of best practice that I've seen, subject to me, myself, and I.

Assuming that's not a typo, the code you have shown is simply creating a property called "index" that houses whatever the index is, and is probably just for instructional purposes.

If that is a typo and it's supposed to be "key", passing index in as key is fine, as you're most likely not going to see the downfall of doing this on this small and insignificant scale, so don't worry about it! It's just to get rid of the error messages that would occur without assigning a key.

The reason why we don't set key as index is because key is a unique, and permanent property that you're assigning. Using key as index will mean that this unique and permanent key is now an easily repeatable number. This will collide with other keys that will have the same number, and will cause errors, show incorrect data, and do all kinds of weird stuff. Best practice I've seen is to basically use key just like _id, by generating a short id with the npm packet called "shortid." With the awesome .generate() method, we can easily create unique ids. A production ready example of this would look like...

function helpSharina(content) {
  return {
    key: shortid.generate(),
    content: content
  }
}