Reactjs Two children with the same key react

119 Views Asked by At

when am trying to Profile info of another user it shows duplicate with this error "Warning: Encountered two children with the same key, the id of user here. Keys should be unique so that components maintain their identity across updates. Non-unique keys may cause children to be duplicated and/or omitted — the behavior is unsupported and could change in a future version."

I tried the index, and it didn't work, and I tried the ID number, and it didn't work either. I'm despaired

this is my code

<div className='ProfileInfo'>
    {userData.length > 0 && userData.map(((user, index) => (
      
      <div className='profileInfo-container' key={index} >

        <div className='profileInfo-top'>
        </div>
        <div className='profileInfo-center'>
          <img className='profile-avatar' fontSize="large" src={auth.user.avatar} alt=""/>
          {user._id && auth && user._id === auth.user._id ? 
          <button className='addfbtn' onClick={()=>setEdit(true)}>EDIT PROFILE</button>
          : <GlobalFriendBtn classBtn="addfbtn" user={user}/>
          }
        </div> ... etc، 

   look at this:
   https://www11.0zz0.com/2023/06/19/07/487328533.png
1

There are 1 best solutions below

1
gazdagergo On

This should work if each user has unique id.

<div className='ProfileInfo'>
  {userData.map(user => (
    <div className='profileInfo-container' key={user._id}>
       ...
    </div>
  ))}
</div>

It might happen that multiple user has undefined or similar id, and that causes the error.


Another note: you do not need to check the length of the array, userData.map will simply render nothing if the array is empty.