I am learning React and I built this app. While running code, I got this warning on console: Warning: Each child in an array or iterator should have a unique "key" prop. Check the render method of ToDos
This is my code:
return (
<div className='container' style={todoStyle}>
<h3 className='my-3'>ToDos List</h3>
{props.todos.length === 0 ?
"No ToDos to display" :
props.todos.map((todo) => {
return (
<>
<ToDoItem todo={todo} key={todo.sno} onDelete={props.onDelete} /> <hr />
</>
)
})
}
</div>
)
I have added key to ToDoItem
yet I am getting this warning.
2
Answers
I did some changes and it worked. I removed hr tag from return statement and returned only ToDoItem and used hr to show horizontal line in ToDoItem.js file. My new code looks like this:
ToDoItem.js:
This warning is coming probably because the unique key prop should be on outermost element in the DOM tree.
Also I’m not sure if
todo.sno
is unique thus implement index from map function to ensure the key prop remains unique.