reactjskey

Warning: Each child in a list should have a unique "key" prop in table


I use the key in <tr key={i}> currently but this warning appears in the console

 <table className="table table-responsive table-striped table-bordered">
     <thead className="text-center">
         <tr>
             <th>شرح خطا</th>
             <th>تاریخ / زمان</th>
             <th>عنوان خطا</th>
             <th>شناسه</th>
         </tr>
     </thead>
     <tbody>
         {
             logs && logs.map((_item, i) => {
                 return <>
                     <tr key={i}>
                         <td  className="text-end">{_item.exception}</td>
                         <td  className="text-center" >{new Date(_item.timeStamp).toLocaleDateString('fa-IR')} {new Date(_item.timeStamp).toLocaleTimeString('fa-IR')}</td>
                         <td  className="text-end">{_item.message}</td>
                         <td  className="text-end">{_item.id}</td>
                     </tr>
                 </>
             })
         }
     </tbody>
 </table>

What is the problem?

How can I fix this?


Solution

  • It's because <></> is actually the top level React component. <> is just a syntactic sugar for <Fragment />. In your case, removing <></> should fix it.

    Do this instead.

    logs && logs.map((_item, i) => {
                 return (
                     <tr key={i}>
                         <td  className="text-end">{_item.exception}</td>
                         <td  className="text-center" >{new Date(_item.timeStamp).toLocaleDateString('fa-IR')} {new Date(_item.timeStamp).toLocaleTimeString('fa-IR')}</td>
                         <td  className="text-end">{_item.message}</td>
                         <td  className="text-end">{_item.id}</td>
                     </tr>
                 )
             })
         }