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>
We have created a
LanguageChangercomponent. AhandleClickfunction determines the url and updates as you have stated buton LanguageChangeddoes not provide the same flexibility imo.I have included two versions of
newUrl. First,enis not present in the url. Second, iflanguageCodeis present in the url.