2

I am using Next.js' built-in internationalisation features to change my app's language and everything is working perfectly except for one undesirable behaviour:

Calling the changeLanguage function results in the page scrolling to the top in spite of setting the router's scroll option to false.

Please note that Next.js - router.push without scrolling to the top and Next.js maintain scroll position when page Routing did not solve my issue.

import { useRouter } from "next/router";
import Select, { components } from "react-select";

const LanguageToggler = () => {

  const router = useRouter();
  const { locale, pathname, locales, asPath } = router;

  const changeLanguage = (e) => {
    const locale = e.value; // is equal to one of these values: ['en', 'sv', 'ru', 'fr']
    router.push(pathname, asPath, { locale }, { scroll: false });
  };

 return (
      <Select
        ...irrelevant
        onChange={changeLanguage}
        components={{
          Option: CustomSelectOption,
        }}
      />
    )
};

export default LanguageToggler;

P.S. The react-select library is used to display a dropdown list of flags, clicking each flag summons changeLanguage to update the locale accordingly.

Y H R
  • 595
  • 5
  • 15

1 Answers1

1

Next router.push accepts three parameters.

router.push(pathname, asPath, { locale }, { scroll: false });

should be

import router from 'next/router';

router.push(pathname, asPath, { locale, scroll: false });
Sean W
  • 5,663
  • 18
  • 31
  • doesn't work either, nextjs 13.4 , tried both and via onClick router.push – Nathan Bernard Jul 04 '23 at 18:49
  • You must make sure that the answers you use are for your use of Next. There are multiple routers now and this is clearly linked to pages directory docs which still functions as answered. – Sean W Jul 05 '23 at 23:51