0

I have a react application and I am struggling to remove the previous page scroll-position.

Please I would appreciate it if you understand my problem before concluding.

I do not want to preserve the scroll history. I want it to always go back to the top of the page.

I have used the solution below to make the application scroll back to the top of the page whenever a user navigates to a new page.

import { useEffect } from 'react';
import { useLocation } from 'react-router-dom';

const ScrollToTop = ({ children }) => {
  const { pathname } = useLocation();

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

  return children || null;
};

export default ScrollToTop;

The above code is working very fine with no issues. What is not working for me is:

When a user clicks a Button I created using Link from react-router-dom they are navigated to the new page (correct page), but the scroll-position is of the previous page (the page they are coming from).

I have tried using these hooks.

  • useLayoutEffect
  • withRouter (is removed from react-router v6)
  • useHistory (is removed from react-router v6
  • useNavigate

They are not working.

How can I resolve this? Or is there something I am missing?

I have also tried implementing the solution below. But wont work.

import { useEffect } from 'react';
import { withRouter } from 'react-router-dom';

    function ScrollToTop({ history }) {
      useEffect(() => {
        const unlisten = history.listen(() => {
          window.scrollTo(0, 0);
        });
        return () => {
          unlisten();
        }
      }, []);
    
      return (null);
    }
    
    export default withRouter(ScrollToTop);
Manasseh Codes
  • 99
  • 1
  • 1
  • 11
  • I am also aware of this solution by Jan, which he considered very unsafe and unprofessional. https://stackoverflow.com/questions/70886149/restore-scroll-position-when-navigating-with-react-router-6 – Manasseh Codes Jul 21 '22 at 09:49

2 Answers2

0

You can scroll to Top every time the user enters that screen, with focus hook https://reactnavigation.org/docs/function-after-focusing-screen/.

Alija Fajic
  • 556
  • 6
  • 17
  • 1
    We can also listen to the 'focus' event with an event listener. After setting up an event listener, we must also stop listening to the event when the screen is unmounted. With this approach, we will only be able to call an action when the screen focuses. This is useful for performing an action such as logging the screen view for analytics. – Manasseh Codes Jul 21 '22 at 11:31
0

After 4 hours of research and trying and errors. I have found the solution to this.

In react-router v6. You do not need to your window. on your useEffect You just need to have your code like this:

useEffect(() => {
    document.body.scrollTo(0, 0); 
});

I found the answer here, and researched more on it.

Manasseh Codes
  • 99
  • 1
  • 1
  • 11