Skip to content

Instantly share code, notes, and snippets.

@mb8z
Last active October 2, 2018 18:14
Show Gist options
  • Save mb8z/a528e4cd075b5056737b49ae108615ce to your computer and use it in GitHub Desktop.
Save mb8z/a528e4cd075b5056737b49ae108615ce to your computer and use it in GitHub Desktop.
// Credit to https://github.com/yahoo/react-intl/issues/416#issuecomment-376088833
// This is a provider that should be a direct child of <IntlProvider> from 'react-intl'.
// Example of wrapping the code:
// <IntlProvider {...someConfigProps}>
// <GlobalIntlProvider>
// <AppLayout />
// </GlobalIntlProvider>
// </IntlProvider>
// This way we can `import { t } from './GlobalIntlProvider'` anywhere in the app
// to use the translations.
// Example usage: pass the `t` as an extra argument in `redux-thunk`, so it can be easilly accessed
import { intlShape } from 'react-intl';
let INTL;
const IntlGlobalProvider = (props, context) => {
INTL = context.intl;
console.log('IntlGloba', { context, props, INTL });
return props.children;
};
IntlGlobalProvider.contextTypes = {
intl: intlShape.isRequired,
};
let instance;
class IntlTranslator {
// Singleton
constructor() {
if (!instance) {
instance = this;
}
return instance;
}
t(id, values) {
return INTL.formatMessage({ id }, values);
}
}
const Translator = new IntlTranslator();
export const { t } = Translator;
export default IntlGlobalProvider;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment