Skip to content

Instantly share code, notes, and snippets.

@Psiiirus
Last active December 6, 2019 10:13
Show Gist options
  • Save Psiiirus/4a5dca61f74d87b78f9d901ac8e0430e to your computer and use it in GitHub Desktop.
Save Psiiirus/4a5dca61f74d87b78f9d901ac8e0430e to your computer and use it in GitHub Desktop.
import * as RNLocalize from 'react-native-localize';
import i18n from 'i18n-js';
import lodash from 'lodash';
import { I18nManager } from 'react-native';
const moment = require('moment'); //load moment module to set local language
require('moment/locale/de'); //for import moment local language file during the application build
//require('moment/locale/en'); //for import moment local language file during the application build
const translationGetters = {
// lazy requires (metro bundler does not support symlinks)
de: () => require('snazz/assets/translations/de.json'),
en: () => require('snazz/assets/translations/en.json'),
};
const translationLocales = Object.keys(translationGetters);
const trans = lodash.memoize(
(key, config) => i18n.t(key, config),
(key, config) => (config ? key + i18n.locale + JSON.stringify(config) : key + i18n.locale),
);
const getLocaleConfig = () => {
const fallback = {
languageTag: 'en',
isRTL: false,
};
const { languageTag, isRTL } =
RNLocalize.findBestAvailableLanguage(translationLocales) || fallback;
return {
locale: languageTag,
isRTL,
};
};
const setI18nConfig = () => {
// fallback if no available language fits
const { locale, isRTL } = getLocaleConfig();
moment.locale(locale); //set moment local language to zh-cn
// clear translation cache
trans.cache.clear();
// update layout direction
I18nManager.forceRTL(isRTL);
// set i18n-js config
i18n.translations = { [locale]: translationGetters[locale]() };
i18n.locale = locale;
};
export {
setI18nConfig,
translationGetters,
trans,
getLocaleConfig,
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment