Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

213
Vistas
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>
about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

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);
    }
  };
about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda