Created
January 2, 2018 22:47
-
-
Save r2dev/13a4c4203dcccd312801d3203c5effb9 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class I18n { | |
constructor(locale) { | |
this.locale = locale; | |
this.subscriptions = []; | |
this.text = window[locale] | |
} | |
setLocale(locale) { | |
if (this.locale !== locale) { | |
this.locale = locale; | |
this.subscriptions.forEach(f => f()); | |
} | |
} | |
subscribe(f) { | |
this.subscriptions.push(f); | |
} | |
getText(id) { | |
this.text[id]; | |
} | |
} | |
class I18nProvider extends React.Component { | |
constructor(p, c) { | |
super(p, c); | |
this.i18n = new i18n(this.props.locale); | |
} | |
componentWillReceiveProps(next) { | |
this.i18n.setLocale(next.locale); | |
} | |
getChildContext() { | |
return { i18n: this.i18n }; | |
} | |
render() { | |
return <React.Fragment>{this.props.children}</React.Fragment>; | |
} | |
} | |
I18nProvider.childContextTypes = { | |
i18n: React.PropTypes.object | |
}; | |
class I18nText extends React.Component { | |
componentDidMount() { | |
this.context.i18n.subscribe(() => this.forceUpdate()); | |
} | |
render() { | |
return this.context.i18n.getText(this.props.id) || this.props.id; | |
} | |
} | |
class I18Paragraph extends React.Component { | |
componentDidMount() { | |
this.context.i18n.subscribe(() => this.forceUpdate()) | |
} | |
render() { | |
return change() | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment