Search code examples
javascriptreactjsscroll

Losing scroll position in DOM-element after sorting array elements


Problem: After sorting the array elements, the scroll position is lost. An interesting fact is that the position of those elements that were moved to the end of the array is lost.

Question: How not to lose the scroll position when sorting an array of elements?

Steps To Reproduce:

  1. Change the scroll position for each DOM element.
  2. Press "btn reverse" button.

The current behavior: The first element saves the scroll position. The second and third elements reset the scroll position.

The expected behavior: All elements must retain their scroll position.

Example code (to scroll all DOM-elements and press "btn reverse"): https://stackblitz.com/edit/react-d2raex?file=src%2FApp.js


Solution

  • With the keys you're using, you're asking the List component to render the same DOM nodes but in different places. It has to remove them to do that. The DOM Element interface doesn't provide any API to reorder elements.

    Original discussion here: https://github.com/facebook/react/issues/24640