Next.js: useRouter not updating locale when changing language via i18n.changeLanguage()

Created on 27 Oct 2020  路  4Comments  路  Source: vercel/next.js

Bug report

Describe the bug

When changing language via a select or toggle using i18n.changeLanguage(), the router active locale does not update to the new language.

To Reproduce

Steps to reproduce the behavior, please provide code snippets or a repository:

  1. app with react-i18next setup with default options
  2. call i18n.changeLanguage() on click or in a select menu and toggle between difference languages/translations
const handleLocaleChange = useCallback(
    (value: Locales) => {
      const localeString: Locales = value as Locales;
      i18n.changeLanguage(localeString);
    },
    [language],
  );

I am getting expected behavior for language translation, but router is not updating.

Expected behavior

i18n config for nextjs would honor the changed language and update url paths accordingly

Screenshots

System information

  • OS: [ Windows]
  • Browser (if applies) edge
  • Version of Next.js: [10.0.0]
  • Version of Node.js: [latest]

Most helpful comment

I think it is up to those packages to leverage the new Next.js i18n capabilities. Since they were announced today it may take some time before those are updated, but probably worth a shot to open an issue there.

All 4 comments

react-i18next, despite the name, has nothing to do with next.js. You need to handle the logic yourself here or have a single source of truth.

@santialbo "The i18n routing support is currently meant to complement existing i18n library solutions like react-intl, react-i18next, lingui, rosetta, and others by streamlining the routes and locale parsing."

I took this as they were supporting these. If anything, would be nice to get some documentation around changing the locale manually (not on detection) and having routes update.

I think it is up to those packages to leverage the new Next.js i18n capabilities. Since they were announced today it may take some time before those are updated, but probably worth a shot to open an issue there.

I was able to get it to work:

const {i18n} = useTranslation();
const router = useRouter();
const {asPath, pathname} = router;

const handleLocaleChange = useCallback(
  (value: Locales) => {
     const localeString: Locales = value as Locales;
     // this handles the route below
     router.replace(pathname, asPath, {locale: localeString, shallow: true});
     i18n.changeLanguage(localeString);
  },
  [language],
);

Thanks guys!

Was this page helpful?
0 / 5 - 0 ratings

Related issues

matthewmueller picture matthewmueller  路  102Comments

ematipico picture ematipico  路  66Comments

timneutkens picture timneutkens  路  250Comments

arunoda picture arunoda  路  103Comments

poyiding picture poyiding  路  73Comments