Is there any way to get the current used localization / locale?
Lest say I have localization files for en and de. My phone language is set to Swedish. How should I know which localization (language) my app is currently using?
Using I18n.currentLocale() Im able to get the phone current locale, but that is not the same as what localization my app is using.
What you want is something I18n.usedTranslation(), which is sadly not available in i18n-js.
But you can recreate it easily:
import I18n from 'react-native-i18n'
import en from '../locales/en'
import fr from '../locales/fr'
// Enable fallbacks if you want `en-US`
// and `en-GB` to fallback to `en`
I18n.fallbacks = true
// Available languages
I18n.translations = { en, fr }
const getUsedTranslation = () => {
const availableTranslations = Object.keys(I18n.translations)
const defaultLocales = I18n.locales.default()
const currentLocale = defaultLocales.find(l => l in availableTranslations)
return typeof currentLocale !== 'undefined'
? currentLocale
: I18n.defaultLocale
}
In that case I would refactor it like this: 馃帀
const getUsedLocale = () => {
const usedLocale = I18n.locales.default().find(l => l in Object.keys(I18n.translations));
return usedLocale || I18n.defaultLocale;
};
@henrikra You fire Object.keys at each iteration of I18n.locales.default() 馃槢
True 馃憤 I think this will make difference at if the array is like 1 000 000 000 items long :D
Thanks @zoontek 馃憤
Most helpful comment
What you want is something
I18n.usedTranslation(), which is sadly not available in i18n-js.But you can recreate it easily: