Leomania
Leomania

Reputation: 89

Set default language using i18next + LanguageDetector

I'm using i18next for the first time in the project. My app has two languages: swedish(sv) and english(en). What I don't understand is that it for some reason sets en to the default language. For example when a user visits the site for the first time. This is my code:

import LanguageDetector from "i18next-browser-languagedetector";
const options = {
  order: ['cookie', 'localStorage', 'sessionStorage', 'navigator', 'htmlTag', 'path', 'subdomain'],
  lookupLocalStorage: 'lng'
}

i18next.use(LanguageDetector).use(initReactI18next).init({
  interpolation: { escapeValue: false },
  detection: options,
  fallbackLng: 'sv',
  supportedLngs: ['sv', 'en'],
  resources: {
      en: {
          common: common_en
      },
      sv: {
          common: common_sv
      },
  },
});

As I set fallbackLng: 'sv', the default language should be Swedish, but it's not? When a user visits the site for the first time, i18n sets lng to en in localstorage. Any ideas?

Upvotes: 5

Views: 5980

Answers (1)

dinh le
dinh le

Reputation: 29

Use this trick in your index.js

if (localStorage.getItem('i18nextLng') === null) {
  localStorage.setItem('i18nextLng', 'sv')
}

i18next.use(LanguageDetector)...

Hope this help!

Upvotes: 2

Related Questions