Reputation: 5
I'm using i18next/i18next-react in my React application. I have it configured as you'd expect with various languages at the root level:
i18n
.use(LanguageDetector)
.use(initReactI18next)
.init({
fallbackLng: "en",
resources: {
en: { ... },
de: { ... },
pl: { ... },
// ...
},
});
The problem I'm running into is this: I want to get the list of languages my i18next instance is currently supporting. I want to know that so I can present a list of options for a language picker and know what I could call i18next.changeLanguage() with.
While that would normally be the same ["en", "de", "pl"]
list I provided to begin with, i18next supports modifying resources during runtime, so it might have changed since. I want to ask i18next directly what its current state is and use it for a source of truth.
My initial guess was that this might be supplied by i18next.languages
but that instead relates to the languages currently active: in the above config, it would be ["en"]
when I'm using English, and ["pl", "en"]
when I'm in Polish, leaving out the fact that "de"
is available in both cases.
I do currently seem to have this option, but it seems a bit like I'm doing something hacky that I shouldn't:
Object.keys(i18n.services.resourceStore.data)
// ["en", "de", "pl"] if the list wasn't modified since
// this definitely reflects changes, too:
i18n.addResourceBundle("ko", "translations", {});
Object.keys(i18n.services.resourceStore.data)
// ["en", "de", "pl", "ko"]
Is this the correct way to do it, or is there a better canonical way to do it?
Upvotes: 0
Views: 564
Reputation: 144
This is my i18next config:
import i18n from 'i18next';
import {initReactI18next} from 'react-i18next';
import en from './lang/en.json';
import cn from './lang/cn.json';
import bh from './lang/bh.json';
const resources = {
en: {
translation: en,
},
cn: {
translation: cn,
},
bh: {
translation: bh,
},
};
export type TSupportedLanguages = keyof typeof resources;
export const SupportedLanguages = Object.keys(
resources,
) as (keyof typeof resources)[]; // I turn object keys to an array
i18n
.use(initReactI18next) // passes i18n down to react-i18next
.init({
compatibilityJSON: 'v3',
resources,
fallbackLng: 'en',
lng: 'en',
interpolation: {
escapeValue: false, // react already safes from xss
},
});
export default i18n;
later i can use SupportedLanguages as an array of Supported Languages
Upvotes: 0