Created
August 11, 2015 03:54
-
-
Save andrewk/cd4927babbeaeaba5653 to your computer and use it in GitHub Desktop.
ReactIntl without mixins
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 provideIntl from './provideIntl'; | |
import ReactIntl from 'react-intl'; | |
const components = {}; | |
export default components; | |
// FormattedMessage, FormattedNumber, FormattedRelative, FormattedDate | |
Object.keys(ReactIntl).forEach(key => { | |
components[key] = provideIntl(ReactIntl[key]); | |
}); |
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'; | |
export default function provideIntl(Component) { | |
class IntlConnection extends React.Component { | |
render() { | |
let intlContext = { | |
locales: this.context.locales, | |
formats: this.context.formats, | |
messages: this.context.messages | |
}; | |
if (this.props.message) { | |
intlContext.message = getIntlMessage(this.context.messages, this.props.message); | |
} | |
return ( | |
<Component {...this.props} {...intlContext} /> | |
); | |
} | |
} | |
IntlConnection.contextTypes = { | |
locales: PropTypes.array, | |
formats: PropTypes.object, | |
messages: PropTypes.object | |
}; | |
return IntlConnection; | |
} | |
// Similar to react-intl's `getIntlMessage` | |
// (It receives the messages as argument) | |
function getIntlMessage(messages, path) { | |
const pathParts = path.split('.'); | |
let message; | |
try { | |
message = pathParts.reduce((obj, pathPart) => obj[pathPart], messages); | |
} finally { | |
if (message === undefined) { | |
throw new ReferenceError('Could not find Intl message: ' + path); | |
} | |
} | |
return message; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment