简体   繁体   中英

How to remove scroll position with react-router v6

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

每次用户进入该屏幕时,您都可以滚动到顶部,使用焦点挂钩https://reactnavigation.org/docs/function-after-focusing-screen/

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM