I'm new in React. I would like to remove this warning. I tried to explore the Web and tried many solutions but none was working for me (key, rowkey, loop, etc.)
Error:
Check the render method of
RankingTable
in tr (created by RankingTable) in RankingTable react_devtools_backend.js:2540:25
Do you have an idea for this issue?
return (
<div className = "overflow-x-auto">
<table className="ranking_table table-auto border-collapse w-full" >
<caption className="sr-only">{ caption }</caption>
<thead>
{
fields.map((field) => (
<tr>
<th>{ field.player }</th>
<th>{ field.total }</th>
<th>{ field.exact }</th>
<th>{ field.good } </th>
</tr>
))
}
</thead>
<tbody>
{
rows.map((row, loop) => (
<tr key={row.key}>
<td>
<span className={`rounded-full rank ranking-${loop 1}`}>{ loop 1 }</span> { row.username },
</td>
<td>
{ row.cntTotal }
</td>
<td>
{ row.cntExact }
</td>
<td>
{ row.cntGood }
</td>
</tr>
))
}
</tbody>
</table>
</div>
)
Thanks!
CodePudding user response:
You're missing the key
in your mapping, like @Shawn Yap said. Make sure to use something unique.
The best way to pick a key is to use a string that uniquely identifies a list item among its siblings. Most often you would use IDs from your data as keys.
The updated thead
should look like this:
<thead>
{
fields.map((field) => (
<tr key={field.<id or something that is unique>}>
<th>{ field.player }</th>
<th>{ field.total }</th>
<th>{ field.exact }</th>
<th>{ field.good } </th>
</tr>
))
}
</thead>
CodePudding user response:
Keys help React identify which items have changed, are added, or are removed. Keys should be given to the elements inside the array to give the elements a stable identity. Source of content https://reactjs.org/docs/lists-and-keys.html#keys
You have to pass unique value in key for each iteration of map. Which must not be repeat through out the loop iteration. If there exist a unique id or any unique value in the fields for each object, then you can pass it in key.
<thead>
{
fields.map((field) => (
<tr key={field.<id or something that is unique>}>
<th>{ field.player }</th>
<th>{ field.total }</th>
<th>{ field.exact }</th>
<th>{ field.good } </th>
</tr>
))
}
</thead>