ZeFifi
ZeFifi

Reputation: 187

How to go to another page without keeping scroll position with React

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.

Upvotes: 1

Views: 1258

Answers (3)

ANUPAM KUMAR
ANUPAM KUMAR

Reputation: 1

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

This code shows the scroll effect but i want to direct open to top without scrolling. You can visit https://react.dev/learn/react-developer-tools, in this page when I click side nav-link in this case open top to page without scrolling.

Upvotes: 0

Suthan Bala
Suthan Bala

Reputation: 3299

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.

Upvotes: 1

Sadeen Alaa
Sadeen Alaa

Reputation: 767

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)
})

Upvotes: 0

Related Questions