'React - splicing a positioned element from an array will cause next index to be rendered
I implemented a chat feature in my react app using websockets that looks like this
The messages are rendered into a new component with the map function. When clicked, an absolute positioned div slides across from the left (translated to 100% on the x axis when hidden and to 0% when in view) with the chat information. It looks like this
When a new message is received, I use the array slice function to pop a chat out of the array and the array unshift function to put it at the start of the array, so that the latest chat always appears at the top. This means that when a chat is open and a new message is received, it is popped out of the the array and the next chat in the array becomes visible.
To be more precise, please refer to the first image. if [email protected] is open and a new message is received, [email protected] becomes active since it is the next in the array.
I know this is the expected behaviour, but is there anyway to go about it and still keep a component visible even after it's position in the array has changed?
Solution 1:[1]
After a bit of intense research I've solved it. When my chat components were rendered, I used the index as the key. When the new message was moved to the top, the indexes were reordered. Using another unique value as the key solves the issue.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Stephen |


