最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

next.js15 - Next.js - router.push with scroll: false still scrolls - Stack Overflow

programmeradmin3浏览0评论

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 });
        }
    }, []);
}

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 });
        }
    }, []);
}

Share Improve this question asked Mar 7 at 17:09 Gios KarrasGios Karras 131 silver badge6 bronze badges
Add a comment  | 

3 Answers 3

Reset to default 1

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./docs/app/api-reference/functions/use-router#disabling-scroll-to-top

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

When using the App Router, we cannot import the router from next/router. Instead, we must use: import { useRouter } from "next/navigation";.

In this case, the router.push function accepts two parameters: router.push(href, options);

So, in my case, I need to update my code like this:

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

With this change, everything works perfectly, and the page no longer scrolls to the top.

Try it like this:

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

Instead of an url which is only the pageNumber query parameters in your case, you can pass the modified router. Doing it this way solved the issue for me.

发布评论

评论列表(0)

  1. 暂无评论