hookrouter
hookrouter copied to clipboard
Scroll to the top behavior
Hi,
When I use the navigate()
function to navigate the user from one page to another, the page scrolling does not update so the new page is loaded scrolled half way through. Am I missing a flag or does the package not have such functionality built in?
As a workaround you can place all your routes in a component. and use the useEffect hook to call window.scrollTo(0,0) like in this code
import { useEffect } from "react";
import { useRoutes } from "hookrouter";
const routes = {
"/": () => "Home",
"/about": () => "about",
"/products": () => "products",
"/products/:id": ({ id }) => `Product ${id}`
};
const Routes = () => {
const Routes = useRoutes(routes);
useEffect(() => window.scrollTo(0, 0));
return Routes || "Not Found";
};
export default Routes;