I’m using React-Router with a custom ScrollToTop
component to reset the scroll position to the top of the page on navigation. However, I have a specific use case where I need the scroll position to stay the same when clicking on category item.
ScrollToTop:
export const ScrollToTop = () => {
const { pathname } = useLocation();
useEffect(() => window.scrollTo(0, 0), [pathname]);
return null;
};
Router:
<BrowserRouter>
<ScrollToTop />
<Routes>
<Route path="/" element={<Layout />}>
<Route path="/" element={<HomePage />}>
<Route path=":category" element={<ExclusiveOffers />} />
</Route>
<Route path=":category/all" element={<AllProductsPage />} />
<Route path=":category/:name" element={<ProductPage />} />
<Route path="/account" element={<AccountPage />} />
<Route path="/checkout" element={<CheckoutPage />} />
</Route>
<Route path="/auth" element={<AuthPage />} />
<Route path="/login" element={<LoginPage />} />
<Route path="/register" element={<RegisterPage />} />
</Routes>
</BrowserRouter>
Category item:
<Box
component={Link}
to={title === "Top Categories"
? `/${item.query}`
: `/${item.query}/all`
}
2
Answers
React Router works on maintaining the same scroll position if we navigate from one route to another. To prevent those we use custom scroll like you did and use overall on routes in app.
For your use case like category item to bypass the custom scroll you can do the following modifications.
1) App.jsx
2) ScrollToTop.jsx
Replace the below with your scroll to top
It will exclude the path which you don’t want to apply scroll top to. Let me know if this fix the problem.
You can accomplish skipping resetting the scroll-to-top a few different ways:
Convert
ScrollToTop
to a layout route to wrap only the routes you want to scroll-to-top:Example Usage:
Update
ScrollToTop
to consume explicit route paths to skip via props:Example Usage:
Note however that
":category"
would match other non-"category" route paths, like"/account"
and"/login"
, so may not be ideal for all scenarios.Pass some link state to skip scrolling to top upon navigating:
Example Usage:
You can use, mix, and apply any of the above implementations to cover more scenarios.