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 :
The warning you’re seeing is because you’re wrapping your <tr> element inside a React fragment (<></>), but the key prop is on the <tr> instead of the fragment. In React, when you return elements inside a fragment, the key should be on the fragment if it’s the top-level element.
Since you’re returning only a single <tr> in each iteration, you don’t need the fragment at all. You can fix the warning by removing the fragment wrapper.
Here’s how you can modify your code:
<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>
By returning the <tr> directly without the fragment, the key prop is correctly applied to the top-level element, and the warning should disappear.