I faced with a strange annoying issue with React - React automatically scrolls the page on re-render.
Demo app on CodeSandbox - https://codesandbox.io/s/react-scroll-bug-demo-y7u50j?file=/src/App.js
Steps to reproduce:
Issue - React automatically scrolls the page when these conditions are met:
So, when the list of items is not visible on screen - no auto scrolling issues. Also, when top of the list is below the top of my screen - no auto scrolling happen as well.
I have created a Vanilla JavaScript app to test if it is Chrome-specific behaviour - no bug, all good - with Vanilla JS there is no scrolling happen when the list of items re-rendered on the screen. It happens only with React app and is very annoying.
As you can see from my CodeSandbox demo:
Expected behaviour - no scrolling happen when the list is re-rendered.
Any idea how to prevent such auto scrolling?
Looks like react is getting confused with keys. If using random values, everything works as expected:
<div key={Math.random()} className="item">
Update
This behavior is called scroll anchoring. You can disable it like this:
.container {
...
overflow-anchor: none;
}