Search code examples
reactjsreact-router-domreact-i18next

How to change/replace window's location locale after changing language using i18next's onLanguageChange listener?


I am currently using React-Router-Dom v6, i18next along with React-i18next.

I want the locale in the location/link to change once the language is switched anywhere inside the app. So I have this listener to check for language change:

./i18n.js

i18n.on('languageChanged', (lng) => {
  const { location } = window;
  location.replace('/ar/', `/${lng}/`).replace('/en/', `/${lng}/`);
});

const baseRouteUrl = '/:locale/';

The thing is, once I reload the page I witness an infinite loop. It is obvious that the upper location replacement is the cause.

How would I modify the listener to ensure no infinite reload/rerender on language change?


Solution

  • Ended up using regex to match language locales and relpace them dynamically:

    i18n.on('languageChanged', (lng) => {
      const { location } = window;
      console.log(location.pathname, 24242424);
      if (location.pathname.match(/\/ar\/|\/en\//) && !location.pathname.includes(`/${lng}`)) {
        const newUrl = location.pathname.replace(/\/ar\/|\/en\//, `/${lng}/`);
        location.replace(newUrl);
      }
    });