next.jsnext.js15

Next.js - router.push with scroll: false still scrolls


I am attempting to add parameters to the URL after navigating to the current page using router.push. However, I don't want the page to scroll to the top after the parameters are added. To prevent this, I am using scroll: false, but unfortunately, it’s not working as expected.

Below is my code:

"use client";

import { useRouter } from "next/navigation";

const MyComponent = ({ pageNumber }) => {

    const router = useRouter();

    useEffect(() => {
        if (!pageNumber || pageNumber === null || pageNumber === "") {
            router.push(`?pageNumber=1`, undefined, { shallow: true, scroll: false });
        }
    }, []);
}


Solution

  • In Next.js 13.5 and above the syntax has changed. The function properties object now comes second.

    Before Next.js 13.5:

      router.push("<new_url>", undefined, { scroll: false })
    

    Next.js 13.5 and above:

    router.push("<new_url>", { scroll: false })
    

    Next.js Official docs: https://nextjs.org/docs/app/api-reference/functions/use-router#disabling-scroll-to-top

    Credit: https://stackoverflow.com/a/77370718/15903427