I am using [email protected]
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
2
Answers
use this code properly works:
import ScrollRestocration from ‘react-router-dom’ and wrap your RouterProvider component with the ScrollRestoration component and seet the onBeforeRestore callback to scroll to the top of the page. In this example, window.scrollTo(0, 0) is used to scroll to the top after that when you navigate to a new route, the page will scroll to the top automaticsally.
The
ScrollRestoration
component also only works with the data routers, so you have to use one of the routers created usingcreateBrowserRouter
,createMemoryRouter
, etc.From the docs:
Create a layout route component to render as the root route element that renders
ScrollRestoration
and anOutlet
for the nested routes.Example: