bajji
bajji

Reputation: 1291

Each child in a list should have a unique "key" prop even though I have defined the key

Below is my react code. I have the key property for each person but I still get the error message.

**

**

import React, { useState } from "react";
import "./App.css";
import Person from "./Components/Person/Person.js";

const App = props => {
  const [currentState, updatePersonState] = useState({
    Persons: [
      { id: "1", name: "abc", age: "37", hobbies: "Cricket" },
      { id: "2", name: "xyz", age: "33", hobbies: "Cook" },
      { id: "3", name: "pqr", age: "07", hobbies: "Reading" }
    ],
    showContent: true,
    buttonText:'Hide Content'
  });

  let persons = "";
  if (currentState.showContent) {
    persons = currentState.Persons.map((person, index) => (
      <div>
        <Person
          name={person.name}
          age={person.age}
          hobbies={person.hobbies}
          **key={person.id}**
        ></Person>
      </div>
    ));
  }

  const toggleHandler = (event, index) => {
    const showContentNow = currentState.showContent;
    updatePersonState({
      ...currentState,
      showContent: !showContentNow,
      buttonText:currentState.showContent?'Show Content':'Hide Content'
    });
  };
  return (
    <div className="App">
      <h1>Styling Components Dynamically</h1>
      <div>
  <button onClick={toggleHandler}>{currentState.buttonText}</button>
      </div>
      <div> {persons}</div>
    </div>
  );
};
export default App;

Upvotes: 0

Views: 183

Answers (2)

Vicky Gonsalves
Vicky Gonsalves

Reputation: 11717

key attribute needs to be on the root element and not on the child element

https://reactjs.org/docs/lists-and-keys.html#keys

persons = currentState.Persons.map((person, index) => (
      <div key={person.id}>
        <Person
          name={person.name}
          age={person.age}
          hobbies={person.hobbies}
        ></Person>
      </div>

However, note that key should be unique among the siblings and it does not need to be unique across the application

Upvotes: 4

MrCharls
MrCharls

Reputation: 167

Don't use plain integers as Keys for React elements (React doesn't like it), this is to prevent problems especially when you have a lot of elements being generated from different loops.

Since multiple elements could have 1 as key (For example) it may cause bugs along the run of the website. I recommend using integers with some identification notation like...

"person_element_${person.id}"

Is basically React telling you to implement good coding practices.

Upvotes: 1

Related Questions