reactjsscroll

How to prevent react from auto scrolling the page on re-render?


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:

  1. I have a vertical list of items.
  2. List re-rendered (items change their order).
  3. List is visible on the screen but the first element is not visible (it is above the screen).

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?


Solution

  • 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;
    }