I have two translations in my app using i18n translator and I'm trying with no success to set the default language.
The preferred language (the default language) will be set at registration and will come from the database.
Where can I create some kind of logic that will tell i18n what is the language coming from the backend?
The value will show something like this:
const defaultLang = currentUser.data.laiso //this will output a string eg. 'en'
The i18n configuration file looks something like this:
import i18n from 'i18next';
import { initReactI18next } from 'react-i18next';
import Backend from 'i18next-http-backend';
import LanguageDetector from 'i18next-browser-languagedetector';
const Languages = ['en', 'de'];
i18n
.use(Backend)
.use(LanguageDetector)
.use(initReactI18next)
.init({
fallbackLng: 'en',
debug: true,
whitelist: Languages,
interpolation: {
escapeValue: false
}
});
export default i18n;
Should be something written under .use(Backend)
?
This is the first time using i18n so any hints would be appreciated.
This is my component where I need the translation. In it, I've tried to set the index of i18n.languages
based on the language preferred, but this is not working:
import React from 'react'
import { useTranslation } from 'react-i18next';
export default function Dashboard() {
//the logged user
const currentUser = AuthService.getCurrentUser();
//value from database
const defaultLang = currentUser.data.laiso //this will output a string eg. 'en'
//translation
const { t, i18n } = useTranslation();
function handleClick(lang) {
i18n.changeLanguage(lang);
}
const current = i18n.languages[defaultLang === 'en' ? 0 : 1]
return (
<>
<div className={styles.languageSelector}>
<a
onClick={ () => handleClick('en') }
style={{ fontWeight: current === "en" ? 800 : 400}}
>
EN
</a>
<a
onClick={ () => handleClick('de') }
style={{ fontWeight: current === "de" ? 800 : 400}}
>
DE
</a>
</div>
<div>{t('translated.stuff')}</div>
</>
)
}