UNPKG

@rockpack/localazer

Version:

This module can help you organize localization in your React application

48 lines (47 loc) 1.75 kB
import { Component } from 'react'; import { isFunction, isDefined, isObject, isString } from 'valid-types'; import { getDefault } from './utils'; import { i18n } from './jed'; export const components = {}; let uid = 0; export const getID = () => uid++; export default class LocalizationObserver extends Component { constructor(props) { super(props); this.changeLocalization(this.props.currentLanguage); } componentDidUpdate(prevProps) { if (this.props.currentLanguage !== prevProps.currentLanguage) { this.changeLocalization(this.props.currentLanguage); } } changeLocalization(locale) { locale = this.props.languages[locale] ? locale : this.props.defaultLanguage; const localeData = this.props.languages[locale] ? this.props.languages[locale] : getDefault(this.props.defaultLanguage, this.props.defaultLocaleData); this.updateComponents(localeData, locale); } updateComponents(localeData, locale) { if (localeData && isObject(localeData.locale_data) && isObject(localeData.locale_data.messages)) { if (isFunction(this.props.onChange) && isString(locale)) { this.props.onChange(locale); } i18n.options = localeData; Object.keys(components) .forEach(id => { if (isDefined(components[id])) { components[id].forceUpdate(); } }); } } render() { return this.props.children; } } LocalizationObserver.defaultProps = { currentLanguage: 'en', defaultLanguage: 'en', languages: {}, defaultLocaleData: null };