Home > Software engineering >  How to go to another page without keeping scroll position with React
How to go to another page without keeping scroll position with React

Time:10-09

I'm working on a project with Next/React. When I click on a button which is supposed to bring me to another page, the scroll position is kept, meaning that I arrive X pixels down on the new page.

I added the following code to the page:

if (window.pageYOffset > 0) {
  window.scrollTo(0, 0);
}

It works. But the thing is, before it works, the page is displayed X pixels down around 1 sec or less before it goes to the top.

CodePudding user response:

Add the scrolling to the top code in the useEffect hook or componentDidMount of your page component. You'll need to add this to every page components. I'd recommend moving it into a custom hook and calling it.

For your useEffect do this:

useEffect(() => window.scrollTo(0, 0), []);

This will ensure once the component is mounted, it will scroll to the top. The empty [] dependency array ensures it only gets executed once when the component is mounted.

CodePudding user response:

There are two ways you can try:

First

ReactDOM.findDOMNode(this).scrollLeft = 0; you can add this code inside componentDidUpdate if it a class component or inside useEffect if it is a function component

Second

history.listen((location, action) => {
    window.scrollTo(0, 0)
})
  • Related