Last active
October 2, 2018 18:14
-
-
Save mb8z/a528e4cd075b5056737b49ae108615ce to your computer and use it in GitHub Desktop.
This file contains hidden or 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
// 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