Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React i18next and correct way of changing language

I am developing a multilanguage application using React, i18next and i18next-browser-languagedetector.

I initialize i18next the following way:

i18n
  .use(LanguageDetector)
  .init({
    lng: localStorage.getItem(I18N_LANGUAGE) || "pt",
    fallbackLng: "pt",
    resources: {
      en: stringsEn,
      pt: stringsPt
    },
    detection: {
      order: ["localStorage", "navigator"],
      lookupQuerystring: "lng",
      lookupLocalStorage: I18N_LANGUAGE,
      caches: ["localStorage"]
    }
  });

export default i18n;

And I have implemented a language selector that just changes the value in the localStorage to what the user chose.

Is this the correct way of doing it?

I ask because even though this works, I feel I am "cheating" by setting localStorage.getItem(I18N_LANGUAGE) || "pt" and that I am not using the language detection as I should.

like image 530
pteixeira Avatar asked Mar 01 '16 16:03

pteixeira


People also ask

How do I change the language in Reactjs?

Changing the Language of the WebsiteCreate the file src/LocaleContext. js with the following content: import React from "react"; const defaultValue = { locale: 'en', setLocale: () => {} } export default React.

How do I change the default language in i18n?

as outlined by the i18n documentation, languages only appear once you've installed the corresponding language pack. Simply search for the language in the vsx-registry view and you should get the option to download and install it. Afterwards you can switch to it using the Configure Display Language command.

What is the difference between i18n and i18next?

i18n is an abbreviation that is used across all the programming languages and software development world. i18next is a JS framework/set of libraries.


1 Answers

According to the documentation, you shouldn't need to specify the language yourself:

import i18next from 'i18next';
import LngDetector from 'i18next-browser-languagedetector';

i18next
  .use(LngDetector)
  .init({
    detection: options
  });

And according to this piece of source in i18next, it indeed uses the detection capabilities of the plugin:

if (!lng && this.services.languageDetector) lng = this.services.languageDetector.detect();

Is this the correct way of doing it?

So, no, it isn't . Let the plugin do it's job. :)

like image 164
Guilherme Rodrigues Avatar answered Oct 09 '22 13:10

Guilherme Rodrigues