November 27, 2022

React-Router Scroll To Top On Every Transition

React 16.8+

If you are running React 16.8+ this is straightforward to handle with a component that will scroll the window up on every navigation:
Here is in scrollToTop.js component

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

export default function ScrollToTop() {
  const { pathname } = useLocation();

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

  return null;

Then render it at the top of your app, but below Router
Here is in app.js

import ScrollToTop from "./scrollToTop";

function App() {
  return (
      <ScrollToTop />
      <App />

Or in index.js

import ScrollToTop from "./scrollToTop";

        <ScrollToTop />
        <App />

Leave a Reply

Your email address will not be published. Required fields are marked *