Last active
April 23, 2018 06:54
-
-
Save cecigarcia/ae33341108795cecbcc3deca1d26392c 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
import React, {Component} from "react"; | |
import translations from "./translations"; | |
class LocaleProvider extends Component { | |
state = { locale: "es" }; | |
// Defines the Context that React should | |
// pass down to any component in the subtree | |
getChildContext() { | |
return { | |
locale: this.state.locale, | |
changeLocale: locale => this.setState({ locale }), | |
}; | |
} | |
render() { | |
return ( | |
{this.props.children} | |
); | |
} | |
} | |
// Defines all value types that | |
// this component will expose in the Context | |
LocaleProvider.childContextTypes = { | |
locale: PropTypes.string, | |
changeLocale: PropTypes.func, | |
}; | |
const T = ({ key }, { locale }) => ( | |
<span> | |
{translations[locale][key]} | |
</span> | |
); | |
// Defines the values which the component | |
// should read from the context | |
T.contextTypes = { locale: PropTypes.string } | |
const LocaleSelector = ({}, { changeLocale }) => ( | |
<span> | |
<button onClick={() => changeLocale("es")}>es</button> | |
<button onClick={() => changeLocale("en")}>en</button> | |
</span> | |
); | |
LocaleSelector.contextTypes = { changeLocale: PropTypes.func } | |
<LocaleProvider> | |
<LocaleSelector /> | |
<T key="msg1" /> | |
<T key="msg2" /> | |
</LocaleProvider> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment