Skip to content

Instantly share code, notes, and snippets.

@whichsteveyp
Created April 2, 2016 17:20
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save whichsteveyp/ed7a3147623ff375259de6afc29d8e40 to your computer and use it in GitHub Desktop.
Save whichsteveyp/ed7a3147623ff375259de6afc29d8e40 to your computer and use it in GitHub Desktop.
Considering usage for React Context - Localization/Utilities
// imports & variables, etc
ReactDOM.render(
<Localization messageBundle={{ foo: 'Welcome', bar: 'This is', baz: 'a website' }}>
<Provider store={Store}>
<Router history={history}>
<Route path="/" component={SomeParentRenderingGrandchildrenThatWantLocalizedStrings}>
</Router>
</Provider>
</Localization>,
document.getElementById('react-app')
);
import React, { PropTypes } from 'react';
const { number, string, func } = PropTypes;
const DisplayGrandchild = (props, context) => {
const { foo, bar, baz } = props;
const { localize } = context;
return (
<div>
<p>{localize(foo)}</p>
<p>{`${localize(bar)}, ${localize(baz)}!`}</p>
</div>
);
};
DisplayGrandchild.propTypes = { foo: string, bar: string, baz: string };
DisplayGrandchild.defaultProps = { foo: '', bar: '', baz: '' };
DisplayGrandchild.displayName = 'DisplayGrandchild';
DisplayGrandchild.contextTypes = { localize: func };
export default DisplayGrandchild;
import React, { PropTypes } from 'react';
const { func, objectOf, string } = PropTypes;
const Localization = React.createClass({
propTypes: {
messageBundle: objectOf(string).isRequired
},
getDefaultProps() {
return {
messageBundle: {}
};
},
childContextTypes: {
localize: func
},
getChildContext() {
return {
localize: this.localize
};
},
localize(key) {
return this.props.messageBundle[key] || key;
},
render() {
return this.props.children;
}
});
export default Localization;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment