Skip to content

Instantly share code, notes, and snippets.

@cecigarcia
Last active April 19, 2018 11:49
Show Gist options
  • Save cecigarcia/2ec042537acdfb90ef144e64a9edcf64 to your computer and use it in GitHub Desktop.
Save cecigarcia/2ec042537acdfb90ef144e64a9edcf64 to your computer and use it in GitHub Desktop.
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