cjmling / findings

Notes on stuff i finds worth keeping for quick reference later on.
2 stars 0 forks source link

Smooth scroll on route change nextjs #351

Open cjmling opened 2 months ago

cjmling commented 2 months ago
  1. Add scroll={false} to

  2. Listen to path change and scroll to Top . Add this code to the component where it get included on every page.

const pathname = usePathname();
  const searchParams = useSearchParams();

  const scrollToTop = () => {
    window.scrollTo({
      top: 0,
      behavior: "smooth",
    });
  };

  useEffect(() => {
    const url = `${pathname}?${searchParams}`;
    console.log("url", url);
    // You can now use the current URL
    // ...

    scrollToTop();
  }, [pathname, searchParams]);