anticol
anticol

Reputation: 647

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

Upvotes: 48

Views: 54032

Answers (4)

userlond
userlond

Reputation: 3818

In Next.js version 13.5 it works like this:

import { useRouter } from 'next/navigation'

const router = useRouter();
router.push("<new_url>", {scroll: false})

So, options are passed via JSON as second parameter. To prevent scroll position change after url update, just add {scroll: false}.

Upvotes: 7

K.A
K.A

Reputation: 1659

if you like to use router.push directly with given destination path including the query values ,

and preventing scroll to top, you can use also :

router.push(`/?page=2`, undefined, { scroll: false });

this is just example , and change it based on you case/ requirements.

i hope the helpful

Upvotes: 16

Md Fazlul Karim
Md Fazlul Karim

Reputation: 353

A weird workaround from me. Just get the particular component in the view. Here's how.

import React, { useEffect, useRef } from 'react';


function MyAccount() {
  const containerRef = useRef(null);

  useEffect(() => {
    setTimeout(() => {
      containerRef.current.scrollIntoView({ behavior: 'smooth' });
    }, 250);
  }, []);

  return (
    <div ref={containerRef}>
   {/* It will be your particular component that needs to be shown  */}
        <UserInformation /> 
    </div>
  );
}

export default MyAccount;

Some people may find it useful! That's why I posted this here. scroll=false is the best solution if you want to retain view.

Upvotes: -1

Gokhan Sari
Gokhan Sari

Reputation: 7924

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

Upvotes: 89

Related Questions