0
votes

OK, so I'm experimenting with ReactJS and i18next.

I want to set my translation language on the initial page load based on some html tag.

For example if I have <html lang="de"> when the page is loaded I would like to have the lng set to de before any translations take place.

Here's the content of my i18n.js file:

import i18n from "i18next";
import { initReactI18next } from "react-i18next";

// the translations
// (tip move them in a JSON file and import them)
const resources = {
  en: {
    translation: {
      "Welcome to React": "Translation in English"
    }
  },
  de: {
    translation: {
      "Welcome to React": "Translation in German"
    }
  }
};

i18n
  .use(initReactI18next) // passes i18n down to react-i18next
  .init({
    resources,
    lng: "en",

    keySeparator: false, // we do not use keys in form messages.welcome

    interpolation: {
      escapeValue: false // react already safes from xss
    }
  });

  export default i18n;
1

1 Answers

1
votes

From here

const htmlLang = document.documentElement.lang; // for <html lang=".."> not xml-lang:".."

Now you can put this constant in youe i18n declaration

i18n
  .use(initReactI18next) // passes i18n down to react-i18next
  .init({
    resources,
    lng: htmlLang,

    keySeparator: false, // we do not use keys in form messages.welcome

    interpolation: {
      escapeValue: false // react already safes from xss
    },
    fallbackLng: ['en', //'fr', ...]
  });

I also add a fallback language