hookrouter icon indicating copy to clipboard operation
hookrouter copied to clipboard

Scroll to the top behavior

Open vi-cat opened this issue 4 years ago • 1 comments

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?

vi-cat avatar Sep 26 '19 07:09 vi-cat

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;

aalouaoui avatar Oct 05 '19 23:10 aalouaoui