Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
633 views
in Technique[技术] by (71.8m points)

javascript - Next.js - router.push without scrolling to the top

I am using router from next by importing useRouter from next/router.

I am trying to find a solution which will not scroll to the top of the page when I change the query of the URL. Is there any solution? I know that Link component from Next has that option, but I need to use Router component. My next version is 10.0.5.

const router = useRouter();

const changeCurrency = (newCurrency) => {
   //Do some stuff here

    Router.push({
        pathname: router.pathname,
        query: { ...router.query, currency: newCurrency.value },
    });
};
question from:https://stackoverflow.com/questions/65902664/next-js-router-push-without-scrolling-to-the-top

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

router.push has a scroll option, it is true by default. You can turn it off like this:

const router = useRouter();

async function navigate(newCurrency) {
  router.push({
    pathname: router.pathname,
    query: { ...router.query, currency: newCurrency.value },
  }, undefined, { scroll: false });
}

router.push accepts the most of (if not all) next/link's props in the options object. You can check them here: https://nextjs.org/docs/api-reference/next/link


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...