Skip to content

Instantly share code, notes, and snippets.

@andrewk
Created August 11, 2015 03:54
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 andrewk/cd4927babbeaeaba5653 to your computer and use it in GitHub Desktop.
Save andrewk/cd4927babbeaeaba5653 to your computer and use it in GitHub Desktop.
ReactIntl without mixins
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]);
});
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