score:8

Accepted answer

You can use some pure JS for that:

window.onbeforeunload = function () {
  window.scrollTo(0, 0);
}

This will make page scroll to top before it reloads, so everything will be fine when reload ends.

score:0

Another way of implementing a Custom Component for Scroll To Top in React-17.0.2 is by using hooks:

Step 1: Create custom component: ScrollToTop.js

import { useEffect } from "react";
import { useLocation } from "react-router";

const ScrollToTop = (props) => {
  const location = useLocation();
  useEffect(() => {
    if (!location.hash) {
      window.scrollTo(0, 0);
    }
  }, [location]);

  return <>{props.children}</>
};

export default ScrollToTop;

Step 2: Call ScrollToTop component into Root:

const App = () => {
  return (
    <>
      <BrowserRouter>
        <Router>
          <ScrollToTop />
    <Switch> ..... </Switch>
            </Router>
      </BrowserRouter>

    </>
  );
}

export default App;
    

Related Query

More Query from same tag