labilouser
labilouser

Reputation: 337

How to set i18n default translation language in React

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>
      </>
    )
}

Upvotes: 8

Views: 31607

Answers (4)

Momen_nasser
Momen_nasser

Reputation: 39

as language detection mechanism uses localstorage by default, best way would be to add below lines before i18n.init({}).

if (!localStorage.getItem('i18nextLng')) {
  localStorage.setItem('i18nextLng', 'ar');
}

if you have an i18n.ts in your src folder, just add above lines before definition of your i18n instance like this:

if(!localStorage.getItem('i18nextLng')) {
  localStorage.setItem('i18nextLng', 'en');
}

i18n
  // detect user languagelanguageDetector
  .use(LanguageDetector)
  // pass the i18n instance to react-i18next.
  .use(initReactI18next)
  // init i18next
  .use(Backend)
  .init(

{

Upvotes: 3

Said Benmoumen
Said Benmoumen

Reputation: 343

you can do that just by adding lng: 'en' inside .init()

.init({
    fallbackLng: 'en',
    lng: 'en', // default language
    debug: true,
    whitelist: Languages,
    interpolation: {
        escapeValue: false
    }
});

https://www.i18next.com/overview/configuration-options

Upvotes: 17

labilouser
labilouser

Reputation: 337

I've managed to solve this by using useEffect.

//set the language from database
  useEffect(() => {
    i18n.changeLanguage(currentUser.data.laiso);
  }, []);

That was it, Thanks

Upvotes: 0

Gh05d
Gh05d

Reputation: 8992

I think you need a hook to rerender the page when the language was changed. So you could add this to your Dashboard.jsx:

  React.useEffect(() => {
    const handleLanguageChange = () => {
      // Refresh your component, maybe use a hook for it.
    };

    i18next.on("languageChanged", handleLanguageChange);

    return () => {
      i18next.off("languageChanged", handleLanguageChange);
    };
  }, []);

And for the refresh logic, you could add a counter which increment when the language is changed, this should be enough to start a rerender of the component.

Upvotes: 0

Related Questions