React i18next and correct way of changing language

pteixeira picture pteixeira · Mar 1, 2016 · Viewed 19k times · Source

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.

Answer

Guilherme Rodrigues picture Guilherme Rodrigues · May 19, 2016

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. :)