Home > Enterprise >  "Each child in a list should have a unique 'key' prop error" despite having a ke
"Each child in a list should have a unique 'key' prop error" despite having a ke

Time:03-23

I have the following error which I am familiar with :

enter image description here

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:
enter image description here

Note: The screenshot above shows the totality of the ids (2).

Edit smoosh-firefly-b0t8gv

CodePudding user response:

{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.

CodePudding user response:

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>
  • Related