Created
June 25, 2017 19:09
-
-
Save wyeo/4bc235cd46b25149d83c8d09efd67d4e to your computer and use it in GitHub Desktop.
Polygot | HOC | React
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, { Children } from 'react' | |
import ReactDOM from 'react-dom' | |
import PropTypes from 'prop-types' | |
import Polyglot from 'node-polyglot' | |
import messages from './message' | |
const locale = window.localStorage.getItem('locale') || 'fr' | |
const polyglot = new Polyglot({ | |
locale, | |
phrases: messages[locale] | |
}) | |
const translate = polyglot.t.bind(polyglot) | |
class ThemeProvider extends React.Component { | |
getChildContext() { | |
return { | |
theme: this.props.theme, | |
translate: this.props.translate | |
} | |
} | |
render() { | |
return Children.only(this.props.children) | |
} | |
} | |
ThemeProvider.propTypes = { | |
theme: PropTypes.object.isRequired, | |
translate: PropTypes.func.isRequired | |
} | |
ThemeProvider.childContextTypes = { | |
theme: PropTypes.object.isRequired, | |
translate: PropTypes.func.isRequired | |
} | |
const themed = (ComponentToWrap) => { | |
class ThemeComponent extends React.Component { | |
render() { | |
const { theme, translate } = this.context | |
return ( | |
<ComponentToWrap {...this.props} theme={theme} translate={translate} /> | |
) | |
} | |
} | |
ThemeComponent.contextTypes = { | |
theme: PropTypes.object.isRequired, | |
translate: PropTypes.func.isRequired | |
} | |
return ThemeComponent | |
} | |
const StatelessComponent = ({ text, theme, translate }) => ( | |
<div style={{ color: theme.color }}> | |
{translate('home')} | |
</div> | |
) | |
const HelloWorld = themed(StatelessComponent) | |
const theme = { | |
color: '#cc3300', | |
fontFamily: 'Georgia' | |
} | |
ReactDOM.render( | |
<ThemeProvider theme={theme} translate={translate}> | |
<HelloWorld text={'HELLO WORLD'} /> | |
</ThemeProvider>, | |
document.getElementById('main') | |
) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment