Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

JavaScript

Sharina Jones
PLUS
Sharina Jones
Courses Plus Student 18,771 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

Lee B
Lee B
1,141 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
  }
}