Home > Software engineering >  Scroll to top on browser back button click react
Scroll to top on browser back button click react

Time:03-30

I need to scroll to top every time the url changes in my project (and on page reload).

Everything is working but I am having a problem with the browser back button. Even if the pathname changes the page doesn't scroll to top as it should, it works on all other cases (page reload and regular link navigation).

I tried to counter that creating a custom hook just for the back button, but it's not behaving how I want. I also tried a bunch of other things, but nothing seems to work as for the browser back button

import { useEffect, useState } from "react";
import { useLocation } from "react-router-dom";

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

  const useBackButton = () => {
    const [isBack, setIsBack] = useState(false);
    const handleEvent = () => {
      setIsBack(true);
    };
    useEffect(() => {
      window.addEventListener("popstate", handleEvent);
      return () => window.removeEventListener("popstate", handleEvent);
    });
    return isBack;
  };

  const backButton = useBackButton();
  console.log(backButton);

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

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

  return null;
};

export default ScrollToTop;

CodePudding user response:

I don't think the beforeunload event is necessary here, but will include it anyway. Instead of using an event listener for the "popstate" event you can use the Edit scroll-to-top-on-browser-back-button-click-react

  • Related