Home > Software engineering >  Restore Scroll Position in react js
Restore Scroll Position in react js

Time:11-24

I am trying to get the scroll position of a div in React. I tried getting the window the scroll values the values are always 0.

  handleScrollPosition(e){

   sessionStorage.setItem("scrollPosition", this.myRef.current!.scrollTop.toString());
       };

  <SearchListWrapper className="TestSL" ref={this.myRef}  onScroll={this.handleScrollPosition} >
 <StyledLink onClick={ () =>{ this.onClickResult(); } } >
 </StyledLink>
</SearchListWrapper>

On click of StyledLink the new page is loaded. When I go back(with browser's back button) from the newly loaded page, I want to restore the position of scroll on SearchListWrapper .

CodePudding user response:

If you want scroll position of the page, what you are doing should work, but remind you, that you won't get scroll until you scroll on entire page height.

If you want to get position of the element relative to the page you can you this method: getBoundingClientRect().top. In JavaScript this is used with followingly:

document.getElementById(element).getBoundingClientRect().top;

But as you are in React you are not supposed to be refering to elements in this way. You should use useRef that you give to the element that you want the position of and then use

yourRef.current.getBoundingClientRect().top

So example of this is:

export default function App() {
  const divRef = React.useRef();
  if (divRef) {
    console.log(divRef.current.getBoundingClientRect().top);
  }
  return (
    <div className="App">
      <h1>Hello CodeSandbox</h1>
      <h2> Start editing to see some magic happen!</h2>
      <div ref={divRef}>Text</div>
    </div>
  );
}

Alternative to this solution to this is here: Get scroll position with Reactjs

CodePudding user response:

Solution

handleScrollPosition(e){
    const scrollTop = document.getElementById("TestSL").scrollTop;
    //use scrollTop here
}
<SearchListWrapper id="TestSL" onScroll={this.handleScrollPosition} >
  • Related