For this, there is an injection-api which allows the use of intl methods within React components. First, you need to wrap your component using injectIntl()
, and then call the desired method using this.props.intl
The following methods are available:
- formatDate: (value: any, options ?: object) => string,
- formatTime: (value: any, options ?: object) => string,
- formatRelative: (value: any, options ?: object) => string,
- formatNumber: (value: any, options ?: object) => string,
- formatPlural: (value: any, options ?: object) => string,
- formatMessage: (messageDescriptor: MessageDescriptor, values ?: object) => string,
- formatHTMLMessage: (messageDescriptor: MessageDescriptor, values ?: object) => string,
Example:
import React, {Component} from 'react'; import {intlShape, injectIntl, defineMessages} from 'react-intl'; const messages = defineMessages({ enUSDescription: { id: 'menu.item_en_us_description', defaultMessage: 'The default locale of this example app.', }, }); class LocalesMenu extends Component { render() { const {formatMessage} = this.props.intl; return ( <menu> <li> <a href="/?locale=en-US" title={formatMessage(messages.enUSDescription)} > en-US </a> </li> </menu> ); } } LocalesMenu.propTypes = { intl: intlShape.isRequired, }; export default injectIntl(LocalesMenu);