Ali Khalouf
Ali Khalouf

Reputation: 63

Change the URL path using I18next-react

Hello there, I can't change the href path (URL) after selecting a new language


import i18n from 'i18next';
import { useTranslation, initReactI18next } from 'react-i18next';
import LanguageDetector from 'i18next-browser-languagedetector';
import I18NextHttpBackend from 'i18next-http-backend';

i18n.on('languageChanged', function (lng) {
  
  if (lng === i18n.options.fallbackLng[0]) {
    if (window.location.pathname.includes('/' + i18n.options.fallbackLng[0])) {
      const newUrl = window.location.pathname.replace(
        '/' + i18n.options.fallbackLng[0]
      );
      window.location.replace(newUrl);
    }
  }
});

i18n
  .use(I18NextHttpBackend)
  .use(LanguageDetector)
  .use(initReactI18next) 
  .init({
    fallbackLng: ['en'], 
    whitelist: ['en', 'de', 'it', 'es'],
    detection: {
      order: ['path', 'cookie', 'htmlTag', 'localStorage', 'subdomain'],
      caches: ['cookie'],
      lookupFromPathIndex: 0,
      checkWhitelist: true,
    },
    backend: {
      loadPath: '/localization/{{lng}}/translation.json',
    },
    interpolation: {
      escapeValue: false,
    },
  });

export default i18n;

I got example.com/undefined/page1

I used this way to import the language path to the Href

export const baseUrl = i18n.language === 'en' ? '' : '/' + i18n.language;

and the link <a>home</a>

 <a className='item'  href={baseUrl + '/'} >  Home </a>

Upvotes: 2

Views: 5149

Answers (1)

kingofsevens
kingofsevens

Reputation: 540

We have created a LanguageChanger component. A handleClick function determines the url and updates as you have stated but on LanguageChanged does not provide the same flexibility imo.

I have included two versions of newUrl. First, en is not present in the url. Second, if languageCode is present in the url.

  /**
   * Handles the language change
   * @param code - updated language
   * @global lang - current set language in state
   */
  let handleChange = (code) => {
    if (lang !== code) {
      // v1 - below lines since 'en' is not present in the url as your baseUrl definition
      let newUrl;
      if (lang === "en") {
        newUrl = window.location.pathname.replace(`/`, `/${code}/`);
      } else if (code === "en") {
        newUrl = window.location.pathname.replace(`/${lang}`, ``);
      } else {
        newUrl = window.location.pathname.replace(`/${lang}`, `/${code}`);
      }
      // v2 - below is the version if language is always present in the url
      // let newUrl = window.location.pathname.startsWith(`/${lang}`) ? window.location.pathname.replace(`/${lang}`, `/${code}`) : window.location.pathname.replace(`/`, `/${code}/`)
      window.location.replace(newUrl);
      localStorage.setItem("i18nextLng", code);  // this writes to the localStorage to keep the change
      setLang(code);  // this is coming from useState 
      i18n.changeLanguage(code);
    }
  };

Upvotes: 1

Related Questions