Last active
April 19, 2018 11:49
-
-
Save cecigarcia/2ec042537acdfb90ef144e64a9edcf64 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"; | |
// Create the LocaleContext with a default value | |
const LocaleContext = React.createContext({ locale: "en", changeLocale: () => null }); | |
class LocaleProvider extends Component { | |
state = { locale: "es" }; | |
render() { | |
const value = { | |
locale: this.state.locale, | |
changeLocale: locale => this.setState({ locale }), | |
}; | |
// The Provider allows all components in the subtree to access the value | |
return ( | |
<LocaleContext.Provider value={value}> | |
{this.props.children} | |
</LocaleContext.Provider> | |
); | |
} | |
} | |
const T = ({ key }) => ( | |
// React will find the closest Provider above and use its value, if | |
// no Provider is found, it will use the defaultValue that was passed to createContext() | |
<LocaleContext.Consumer> | |
// The Consumer requires a function as a child which receives the current context value | |
// and returns a React node | |
{({ locale }) => <span>{translations[locale][key]</span>} | |
</LocaleContext.Consumer> | |
); | |
const LocaleSelector = () => ( | |
<LocaleContext.Consumer> | |
{({ changeLocale }) => ( | |
<> | |
<button onClick={() => changeLocale("es")}>es</button> | |
<button onClick={() => changeLocale("en")}>en</button> | |
</> | |
)} | |
</LocaleContext.Consumer> | |
); | |
<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