最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - How to set i18n default translation language in React - Stack Overflow

programmeradmin1浏览0评论

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

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>
      </>
    )
}
Share Improve this question edited Jan 27, 2021 at 14:56 labilouser asked Jan 27, 2021 at 14:45 labilouserlabilouser 3371 gold badge3 silver badges12 bronze badges 1
  • You may need to implement a custom language detector: i18next.com/misc/creating-own-plugins.html#languagedetector – adrai Commented Feb 4, 2021 at 14:15
Add a comment  | 

4 Answers 4

Reset to default 17

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

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(

{

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.

I've managed to solve this by using useEffect.

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

That was it, Thanks

发布评论

评论列表(0)

  1. 暂无评论