Skip to content

Instantly share code, notes, and snippets.

@quarrant
Created April 24, 2019 19:21
Show Gist options
  • Save quarrant/5d1a7fc156daadd4fdbe03b32ed05978 to your computer and use it in GitHub Desktop.
Save quarrant/5d1a7fc156daadd4fdbe03b32ed05978 to your computer and use it in GitHub Desktop.
import { observable, action, computed } from 'mobx';
import { Platform, NativeModules } from 'react-native';
import replace from 'lodash/replace';
enum Locales {
ru = 'ru',
en = 'en'
}
type TLocale = keyof typeof Locales;
type TLocales = { [key in TLocale]: string };
type TDictionary = { [key: string]: TLocales };
class Localization {
@observable private _locale: TLocale;
@observable private dictionary: TDictionary;
constructor(dictionary: TDictionary, locale?: TLocale | undefined) {
this._locale = this.processDefaultLocale(locale);
this.dictionary = dictionary;
}
private processDefaultLocale(locale: TLocale | undefined) {
if (locale) return locale;
return Platform.select({
ios: NativeModules.SettingsManager.settings.AppleLocale,
android: NativeModules.I18nManager.localeIdentifier
}).substring(0, 2);
}
@computed get locale() {
return this._locale;
}
@action switch(locale: TLocale | undefined) {
this._locale = this.processDefaultLocale(locale);
}
translate(text: string, params: Record<string, any> = {}) {
if (
this.dictionary &&
this.dictionary[text] &&
this.dictionary[text][this._locale]
) {
return Object.keys(params).reduce((acc: string, param) => {
return replace(acc, new RegExp(`{${param}}`, 'g'), params[param]);
}, this.dictionary[text][this._locale]);
}
return text;
}
}
export default new Localization({
"someText": {
"ru": "Какой-то текст",
"en": "Some text"
}
});
@quarrant
Copy link
Author

@observer
export default class Example extends React.Component {
  componentDidMount() {
    Localization.switch('ru')
  }

  render() {
    return <Text>{Localization.translate('someText')}</Text>
  }
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment