Home > OS >  Each child in a list should have a unique "key" prop in table React
Each child in a list should have a unique "key" prop in table React

Time:02-05

I don't know where is the error I'm getting in the console, everything seems fine, does anyone have any idea what could be wrong?

Unique key error

<TableBody>
   {announcements.map((announcement) => (
       <TableRow
          key={announcement.id}
          sx={{ '&:last-child td, &:last-child th': { border: 0 } }}
        >
        <TableCell align="left">
            <Box display='flex' alignItems='center'>
                <Avatar src={announcement.photoUrl} alt={announcement.announcementTitle}
                   style={{ height: 50, width: 50, marginRight: 20 }} />
                   <span>{announcement.announcementTitle}</span>
             </Box>
         </TableCell>
         <TableCell align="right">
             <Button onClick={() => handleSelectAnnouncement(announcement)} startIcon={<Edit />} />
              <Button startIcon={<Delete />} color='error' />
          </TableCell>
         </TableRow>
   ))}
</TableBody>

After changing to key={index} I get this error, but I still don't know what is wrong. There are only 6 ID fields in the database, and it can't be duplicated anywhere.

warning after update key

CodePudding user response:

Most probably here you have a duplicate announcement.id values you can fix it like this use the index as key it will be always unique :

{announcements.map((announcement,index) => (
 <TableRow
 key={index}
 sx={{ '&:last-child td, &:last-child th': { border: 0 } }} > ... </TableRow>

CodePudding user response:

You are likely passing some undefined or null value to the key prop. Check whether every announcement object has an string id property.

However, it's not recommended to use the array index as unique key when the array comes from a database (or will change at some point).

  • Related