Created
April 2, 2016 17:20
-
-
Save whichsteveyp/ed7a3147623ff375259de6afc29d8e40 to your computer and use it in GitHub Desktop.
Considering usage for React Context - Localization/Utilities
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
// 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') | |
); |
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, { 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; |
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, { 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