Home > Software engineering >  React - Each child in a list should have a unique 'key' prop
React - Each child in a list should have a unique 'key' prop

Time:10-22

As my first react project, I decided to try and make a Pokedex. I have an array of Pokemon and that I pass into a List component and use the .map() function to render. I understand that the root-most element of that the .map() function returns needs a unique key and I understand that it is ideal if the key can be truly unique to the item so that if the list is sorted, items have the same key. Therefore, I figured using the 'id' of the pokemon would be ideal. I believe I have done that but I cannot get rid of the warning in console. I'd really appreciate a hand with this.

export default class List extends React.Component {
  render() {
    const { list, nav } = this.props;
    return (
      <div className="list">
        {list.map((pokemon) => (
          <PokemonItem key={pokemon.id} navigation={nav} pokemon={pokemon} />
        ))}
      </div>
    );
  }
}

PokemonItem Render Method

render() {
    const { pokemon, navigation } = this.props;
    return (
      <div onClick={() => {
          navigation.navigate("Details", { pokemon });
        }}
        className={"list-item bg_"   pokemon.types[0]}>
        <div className="header">
          <div className="name">{pokemon.name}</div>
          <div className="id">#{this.getId(pokemon.id)}</div>
        </div>
        <div className="body">
          <div className="types">
            {pokemon.types.map((type) => {
              return <div className="type">{type}</div>;
            })}
          </div>
          <div className="sprite">
            <img src={pokemon.imgURL} alt={pokemon.name} title={pokemon.name}></img>
          </div>
        </div>
        <div className="background-image">
          <img src={PkBall} alt="" />
        </div>
      </div>
    );
  }

Warning message showing in console

CodePudding user response:

After the edit of the OP's question the warning occurs here:

<div className="types">
            {pokemon.types.map((type) => {
              return <div className="type">{type}</div>;
            })}
</div>

The key-property is not set for div and should be done like in the first method. If type is unique you can use this as key.

CodePudding user response:

Checking your PokemonItem it reveals that the reason may be laying in this piece of code:

{pokemon.types.map((type) => {
    return <div className="type">{type}</div>;
})}

This is easily fixed by adding the key attribute:

{pokemon.types.map((type) => {
    return <div className="type" key={type.id}>{type}</div>;
})}

You need to add a key in every item returned from a map in order to avoid this error. Also I advice you to add the console output related to your question in the body so it's easier to pinpoint the errors.

  • Related