Search code examples
javascriptreactjsreact-routerreact-router-dom

Scrolling to top when the route changes in React router dom


I am using react-router-dom@6.16.0 and I am facing a problem. The routing is working fine but when I am in the middle of the page and click on any link in my navbar or any other link to route to another page the next page opens from the center and not from the top. After some digging, I discovered that there is a ScrollRestoration component from react-router-dom that can be used to scroll to the top instead of the traditional useEffect scroll to top solution. But in the example that they have given, I didn't understand how to use it inside createBrowserRouter.

Here is the code from my app.js file:

import { RouterProvider, createBrowserRouter } from 'react-router-dom'
import {
  Courses,
  Error,
  Home,
  HomeLayout,
  Login,
  Register,
  Testing,
  Course,
  Contact,
  About,
  FAQ,
  Events,
  EventDetails,
  Library,
  Admin,
} from '@/pages'

const router = createBrowserRouter([
  {
    path: '/',
    element: <HomeLayout />,
    errorElement: <Error />,
    children: [
      {
        index: true,
        element: <Home />,
      },
      {
        path: 'courses',
        element: <Courses />,
      },
      {
        path: 'single-course',
        element: <Course />,
      },
      {
        path: 'testing',
        element: <Testing />,
      },
      {
        path: 'contact',
        element: <Contact />,
      },
      {
        path: 'about-us',
        element: <About />,
      },
      {
        path: 'faq',
        element: <FAQ />,
      },
      {
        path: 'events',
        element: <Events />,
      },
      {
        path: 'event-details',
        element: <EventDetails />,
      },
      {
        path: 'library',
        element: <Library />,
      },
    ],
  },
  {
    path: '/login',
    element: <Login />,
  },
  {
    path: '/register',
    element: <Register />,
  },
  {
    path: '/admin',
    element: <Admin />,
  },
])

const App = () => {
  return <RouterProvider router={router} />
}

export default App

Solution

  • The ScrollRestoration component also only works with the data routers, so you have to use one of the routers created using createBrowserRouter, createMemoryRouter, etc.

    From the docs:

    IMPORTANT

    This feature only works if using a data router, see Picking a Router

    You should only render one of these and it's recommended you render it in the root route of your app

    Create a layout route component to render as the root route element that renders ScrollRestoration and an Outlet for the nested routes.

    Example:

    import { RouterProvider, createBrowserRouter, Outlet } from 'react-router-dom'
    ...
    
    const AppLayout = () => (
      <>
        <ScrollRestoration />
        <Outlet />
      </>
    );
    
    const router = createBrowserRouter([
      {
        element: <AppLayout />,
        children: [
          {
            path: '/',
            element: <HomeLayout />,
            errorElement: <Error />,
            children: [
              { index: true, element: <Home /> },
              { path: 'courses', element: <Courses /> },
              { path: 'single-course', element: <Course /> },
              { path: 'testing', element: <Testing /> },
              { path: 'contact', element: <Contact /> },
              { path: 'about-us', element: <About /> },
              { path: 'faq', element: <FAQ /> },
              { path: 'events', element: <Events /> },
              { path: 'event-details', element: <EventDetails /> },
              { path: 'library', element: <Library /> },
            ],
          },
          { path: '/login', element: <Login /> },
          { path: '/register', element: <Register /> },
          { path: '/admin', element: <Admin /> },
        ]
      },
    ]);
    
    const App = () => {
      return <RouterProvider router={router} />
    };
    
    export default App;