Skip to content

Instantly share code, notes, and snippets.

@cecigarcia
Last active April 23, 2018 06:54
Show Gist options
  • Save cecigarcia/ae33341108795cecbcc3deca1d26392c to your computer and use it in GitHub Desktop.
Save cecigarcia/ae33341108795cecbcc3deca1d26392c to your computer and use it in GitHub Desktop.
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