'"Each child in a list should have a unique 'key' prop error" despite having a key
I have the following error which I am familiar with :
However this time I don't understand why it's here.
Here is my code:
Chat.js
...
{
chats.map(chat => (
<div key={chat._id} id={chat._id}> // <--- line 200
<input
checked={
chat._id === selectedChat?._id
}
id="selectedChat"
name="selectedChat"
onChange={e => handleSelectChat(e)}
type="radio"
value={chat._id}
/>
<label htmlFor="selectedChat">
{chat._id}
</label>
<button
onClick={e => handleDeleteChat(e)}
type="submit"
>
X
</button>
<br />
</div>
))
}
The chat._id exists and work as intended when I inspect the html:
Note: The screenshot above shows the totality of the ids (2).
Solution 1:[1]
I have an other .map() in the page which had an incorrect key (replacing msg._id with msg.id fixed it).
The .map() of the messages is not nested in the other .map() that was pointed by the error logs at line 200, which was confusing and made it much harder to find the origin of the problem.
{chats.map((chat, index) => (
<div key={index} id={index}> // <<< Logged error (line 200)
...
</div>
))}
<div style={{background: "lightblue",maxHeight: "250px",overflow: "auto",}}>
{
...
selectedChat.messages.map(msg => (
<div key={msg._id} ref={scrollRef}> // <<< Actual error
...
</div>
))
}
</div>
Solution 2:[2]
{chats.map((chat, idx) => (
<div key={idx} id={chat._id}>
<input
checked={chat._id === selectedChat?._id}
id="selectedChat"
name="selectedChat"
onChange={(e) => handleSelectChat(e)}
type="radio"
value={chat._id}
/>
<label htmlFor="selectedChat">{chat._id}</label>
<button onClick={(e) => handleDeleteChat(e)} type="submit">
X
</button>
<br />
</div>
))}
Try this, should fix it.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | |
| Solution 2 | Nicolai Christensen |

