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
3 Answers
Reset to default 1In 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.
发布者:admin,转转请注明出处:http://www.yc00.com/questions/1744916417a4600861.html
评论列表(0条)