Open Phurba-Sherpa opened 1 month ago
When you're rendering a list of items using map
in react, react relies on unique keys to properly update the virtual dom. Using duplicate keys can cause unexpected behaviors which includes duplicate items being rendered. Different unexpected behaviors can happen throughout different versions when using non-unique keys.
I think this is expected because id should be unique already written in document how to render list. I suggest to you to use index
of array instead of id
in object to make each item unique.
+{records.map(({ id, name, email }, index) => (
<div
onClick={() => console.log("I am clicked", id)}
- key={id}
+ key={index}
className="grid grid-cols-5 border mb-2 p-2 hover:cursor-pointer"
>
<p>{id}</p>
<p className="col-span-2">{email}</p>
<p className="col-span-2"> {name}</p>
</div>
))}
I think this is expected because id should be unique already written in document how to render list. I suggest to you to use
index
of array instead ofid
in object to make each item unique.+{records.map(({ id, name, email }, index) => ( <div onClick={() => console.log("I am clicked", id)} - key={id} + key={index} className="grid grid-cols-5 border mb-2 p-2 hover:cursor-pointer" > <p>{id}</p> <p className="col-span-2">{email}</p> <p className="col-span-2"> {name}</p> </div> ))}
While this can fix the issue, I suggest checking why record ids are the same to begin with. Having several entries in the DB with the same key can and will cause a headache in the future (assuming these records are from an actual DB).
In any case, index isn't the safest value to send as key, because the index can change for the same item somewhere down the line, due to user interaction with a rendered list for example.
When rendering a list with duplicate keys, React incorrectly renders an extra item, which is interactable, despite the console logging the correct number of items. This behavior occurs even though the data source has the correct number of items.
React version: ^18.0.0
Steps To Reproduce
$ npx create-react-app my-app
$ cd my-app
$ npm run start
Link to code example: https://codesandbox.io/p/sandbox/ylr42w
The current behavior
The expected behavior