1

A page in a React always scrolls to the top on history navigation. I have trouble figuring out what causes the scroll-to-top.

  • There is no window.scrollTo() that does this
  • There is no .focus() event that focuses on an element higher up and moves scroll position
  • The big React components do not unmount which would cause the page to be shorter, which would move scroll position

So what else is there that can cause document.documentElement.scrollTop to be set to 0?

Michael Johansen
  • 3,702
  • 2
  • 20
  • 34

1 Answers1

1

Is there any fallback screen involved in the transition, may be a loading/intermediate frame with minimum height.. You can work on something like mentioned React Router v4 - Keep scrolling position when switching components

function buttonClick() {
    document.getElementById("myDiv").classList.add("reduceHeight");
    setTimeout(()=>document.getElementById("myDiv").classList.remove("reduceHeight"),2000);
  }
#myDiv {
  border: 1px solid black;
  width: 100vw;
  height: 200vh;
  overflow: scroll;
}
#myDiv.reduceHeight {
  width: 80vw;
  height: 90vh;
}
button {
  position: fixed;
  top:100px;
  right:100px;
  z-index:100;
  width:200px;
}
<!DOCTYPE html>
<html>
<body >
<div id="myDiv">
  Scroll and Click the Simulate Button
  
</div>

<button onClick="buttonClick()">Simulate intermediate!</button>
</body>
</html>
Karthikeyan
  • 318
  • 1
  • 8