Yahfi Ilham
Yahfi Ilham

Reputation: 119

React Js Warning: Each child in a list should have a unique "key" prop

enter image description here I got an error message as above, I don't understand even though I have written key props, what should I do? I attach my code like in the picture

Upvotes: 6

Views: 3689

Answers (3)

Connor
Connor

Reputation: 91

TLDR:

You would need to add a key to the outermost jsx element in the callback function of your map. In your case this would the Fragment (<>). Here is the section in the documentation with some examples.

Explanation:

So why does React want me to add keys?

React prefers unique keys assigned to each element so that it can keep track of which particular elements need to be updated in the next render. These keys can help precisely narrow down which parts of the DOM need to be updated. This is one of the awesome parts about react, instead of rebuilding the whole DOM tree on each re-render, only the parts that changed will get rebuilt!

So what happens if I don't add keys?

React won't know the particular elements that need to be updated and will be forced to update more things than it needs to.

Upvotes: 1

Sharp Dev
Sharp Dev

Reputation: 970

Each element in your map should have a unique key... Simply stated your element <>....</> does not have a key prop.... Instead use a React Fragment like such <React.Fragment key={todo.todo_id}/>...</React.Fragment> That way each element (React.Fragment) has a unique key (make sure todo_id is a unique key). Of course you could use a div, but if you don't want a div rendered use React.Fragment.

Upvotes: 3

Skatox
Skatox

Reputation: 4284

The problem is that you're setting the key on a element that's not the root of the loop (the one that gets repeated).

So you'll need to put the key on <> like this:

{todos.map( todo => {
    return {
      < key={todo.todo_id}>
       .......

I would change it to a div, but it's my opinion:

{todos.map( todo => {
    return {
      <div key={todo.todo_id}>
       .......

Upvotes: 3

Related Questions