Introduction
info
React-i18n Package allows the internationalization and localization of your application.
How to generate translation files
After package installation a folder locales
with two json files (en, it) will be generated.
Inside those files there are components translation strings. The standard pattern in use to define them is :
"package.tag.component name.element name.string description" : "Message to translate"
example:
"ui.categoriesPopular.button.showMore": "Show More"
Usage in components
There are two ways to declare and use translations:
Method 1 steps:
- import
defineMessages
anduseIntl
hook from react-intl API. - Define a
messages
constant that will contain the objs with description strings you want to translate. - Inside your functional component, declare a
intl
constant that usesuseIntl
hook. - Refer the message string to be translated inside the textual component inside your render function.
//Import
import {defineMessages, useIntl} from 'react-intl';
// Outside component
const messages = defineMessages({
categoryFollowers: {
id: 'ui.category.categoryFollowers',
defaultMessage: 'ui.category.categoryFollowers'
}
});
//Inside component state
const intl = useIntl();
//Inside JSX Render
`${intl.formatMessage(messages.categoryFollowers)}`
Method steps:
- import
FormattedMessages
from react-intl API - Use
FormattedMessages
component withid
anddefaultMessage
string as defined in your JSON files.
//Import
import {FormattedMessage} from 'react-intl';
//Inside JSX Render
<FormattedMessage id="ui.categoriesSuggestion.noResults" defaultMessage="ui.categoriesSuggestion.noResults" />