react-intl-context
Tiny React Component binds language files with React Context.
Installation
yarn add react-intl-context react
Usage
Single Intl
IntlProvider
at the top of your app
Add Recommend to include your language file during the building process
;;;;; /** * locale value in String * e.g. "en-us" */const LOCALE = processenvBUILD_LOCALE;/** * locale messages in JSON or Object * e.g. { * "test": "test", * "roleInfo": "I am a {role}.", * } */const MESSAGES = processenvBUILD_LOCALE_MESSAGES; const propTypes = history: PropTypesobjectisRequired; const Router = <ConnectedRouter history=propshistory> <IntlProvider locale=LOCALE messages=MESSAGES > <App /> </IntlProvider> </ConnectedRouter>; RouterpropTypes = propTypes;;
IntlConsumer
to component that need translations with injectIntl
HOC
Inject ;;; const propTypes = intl: PropTypesobjectisRequired; /** * this.props.intl = { * locale: PropTypes.string. * messages: PropTypes.objectOf(PropTypes.string), * formatMessage: ({ * id: PropTypes.string, // message key * defaultMessage: PropTypes.string, // message defaultValue if message key is missing in locale files * }, { * [variableKey]: [variableValue], // custom variables * ... * }) => PropTypes.string // message value * } */ { const roleMap = 'en-us': 'student' 'zh-cn': '学生' ; const formatMessage locale = thispropsintl; return <p></p> <p></p> ; } ViewpropTypes = propTypes;View;
Multi Intl
MultiIntlProvider
at the top of your app
Add Recommend to include your language file during the building process
;;;;; /** * default locale value in String * e.g. "en-us" */const DEFAULT_LOCALE = processenvBUILD_DEFAULT_LOCALE;/** * locale message map in JSON or Object * e.g. { * "en-us": { * "test": "test", * "roleInfo": "I am a {role}.", * }, * "zh-cn": { * "test": "测试", * "roleInfo": "我是一个{role}。", * } * } */const MESSAGE_MAP = processenvBUILD_LOCALE_MESSAGE_MAP; const propTypes = history: PropTypesobjectisRequired; const Router = <ConnectedRouter history=propshistory> <MultiIntlProvider defaultLocale=DEFAULT_LOCALE messageMap=MESSAGE_MAP > <App /> </MultiIntlProvider> </ConnectedRouter>; RouterpropTypes = propTypes;;
IntlConsumer
to component that need translations with injectIntl
HOC
Inject ;;; const propTypes = intl: PropTypesobjectisRequired; /** * this.props.intl = { * locale: PropTypes.string. * messages: PropTypes.objectOf(PropTypes.string), * formatMessage: ({ * id: PropTypes.string, // message key * defaultMessage: PropTypes.string, // message defaultValue if message key is missing in locale files * }, { * [variableKey]: [variableValue], // custom variables * ... * }) => PropTypes.string // message value * } */ { const roleMap = 'en-us': 'student' 'zh-cn': '学生' ; const formatMessage locale = thispropsintl; return <p></p> <p></p> ; } ViewpropTypes = propTypes;View;