Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 },
    });
};
like image 785
anticol Avatar asked Jan 26 '21 13:01

anticol


1 Answers

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

like image 196
Gokhan Sari Avatar answered Oct 26 '22 02:10

Gokhan Sari