15
votes

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.

4
I'm trying to solve the same problem and found two solutions. First: you can store locale as url parameter (:locale\you_url) like this. The second is your variant - store locale in localStorage or cookies. I would like to do the same as you, but i18next doesn't find keys. Can you write an example or share your code, please? - qwe asd
We chose to set the locale in the localStorage. What do you mean i18next doesn't find the keys? I am using react-i18next, by the way. Check this: gist.github.com/pteixeira/4a75160ca15e3edf6975 I also have a language selector component that sets the localStorage entry with the value of the language when it initializes, checking for a default value or what the user choses. - pteixeira
Thanks, it's realy helpful for me. One more question: is there way to change language in runtime? - qwe asd
What do you mean in runtime? If you're asking while the application is running, in that language selector component I mentioned in the comment above I added an event listener to a select component that has the language options that we support and we set the language by using i18n.changeLanguage(ev.target.value); (i18nis from i18next) and localStorage.setItem(I18N_LANGUAGE, ev.target.value);. Hope it was useful :) - pteixeira

4 Answers

8
votes

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

3
votes

I think you are very close. You can just set i18n with fallback language initially. And then after loading saved language information for localstorage or localforage or whatever storage, call i18nInstance.changeLanguage(lng).

3
votes

Hopefully this helps someone in the future. The documentation doesn't exactly give you the full picture of how to set up detection, and then I found a closed Github issue where several people were asking a reasonable question, and the maintainers were kinda rude in their responses but also happened to supply a link that should have been in the documentation - but is referenced absolutely no where outside of that Github comment. That example cleared up my issue with a few small adjustments from what the current documentation states to do.

I was then able to get language detection in my url with https:www.domain.com?lng=es as well as when using a browser extension that let me change the browser language.

Heres my working i18n.ts file:

import i18n from 'i18next'
import LanguageDetector from 'i18next-browser-languagedetector'
import { initReactI18next } from 'react-i18next'
import XHR from "i18next-http-backend" // <---- add this

import commonDe from './locales/de/common.json'
import commonEn from './locales/en/common.json'
import commonEs from './locales/es/common.json'
import commonFr from './locales/fr/common.json'

const resources = {
  de: { common: commonDe },
  en: { common: commonEn },
  es: { common: commonEs },
  fr: { common: commonFr }
}

const options = {
  order: ['querystring', 'navigator'],
  lookupQuerystring: 'lng'
}

i18n
  .use(XHR) // <---- add this
  .use(LanguageDetector)
  .use(initReactI18next)
  .init({
    // lng: 'en' // <--- turn off for detection to work
    detection: options,
    resources,
    ns: ['common'],
    defaultNS: 'common',
    fallbackLng: 'en',
    supportedLngs: ['de', 'en', 'es', 'fr'],
    interpolation: {
      escapeValue: false,
    },
    debug: false,
  })

export default i18n

(bonus help - if theres anyone jammed up on this part)

I am working in a Next.js project, and the above file was loaded in the project-root/pages/_app.tsx file like this:

import React from 'react'
import { AppProps } from 'next/app'
import '../i18n/i18n'

import '../public/styles.css'

const TacoFridayApp = ({ Component, pageProps}: AppProps): JSX.Element => {
  
  return <Component {...pageProps} />
}

export default TacoFridayApp
0
votes

@firstdoit:

Good answer with regards to automatic browser language detection. However, don't you think that, it is a better approach of having both the automatic and manual configuration availed to a user.

For instance, if one has a browser set to english, this will be ok for the automatic approach you are suggesting based on the documentation. Should a user change a page language from English to French, this doesn't affect the browser language hence keeping the site only in english because configurations are set to automatically detect browser language.

I, in turn, will give priority to the current page language:

  • Either passed via parameters (/george.php?lang=fr or /fr_FR/george.php)

This will turn be passed as props to my code as a prority as follow

  • var lang = this.props.lang || this.services.languageDetector.detect() || "en";

What's your take?