|
|
Translations can be stored directly in the `i18n.js`, or in separate JSON files imported there in order to keeping things more readable. See documentation for how JSON files can be formatted: [https://www.i18next.com/misc/json-format#json-format](https://www.i18next.com/misc/json-format#i-18-next-json-v3) For example, keys can be nested.
|
|
|
|
|
|
Namespaces can be helpful for structuring the JSON files and to restrict which translations to load when, see documentation: [https://www.i18next.com/principles/namespaces](https://www.i18next.com/principles/namespaces)
|
|
|
|
|
|
There are two main options to use for translations:
|
|
|
|
|
|
## useTranslation hook
|
|
|
|
|
|
The `useTranslation` hook with its `t` function can be used inside most functional components
|
|
|
|
|
|
**Example**:
|
|
|
|
|
|
import React from 'react';
|
|
|
import { useTranslation } from 'react-i18next';
|
|
|
|
|
|
export function MyComponent() {
|
|
|
**const { t, i18n } = useTranslation();
|
|
|
// or const [t, i18n] = useTranslation();**
|
|
|
|
|
|
return <p>{**t('my translated text')**}</p>
|
|
|
}
|
|
|
|
|
|
// Stored translation in the English translations JSON:
|
|
|
// "my translated text": "This is the text."
|
|
|
// In the German translations JSON:
|
|
|
// "my translated text": "Dies ist der Text."
|
|
|
|
|
|
**Documentation**: [https://react.i18next.com/latest/usetranslation-hook](https://react.i18next.com/latest/usetranslation-hook)
|
|
|
|
|
|
## Trans component
|
|
|
|
|
|
In case react nodes should be integrated into a translated text, e.g. there is a link inside or a plural form of a text, use the `Trans` component
|
|
|
|
|
|
**Example**:
|
|
|
|
|
|
function MyComponent({ person, messages }) {
|
|
|
const { name } = person;
|
|
|
const count = messages.length;
|
|
|
|
|
|
return (
|
|
|
**<Trans i18nKey="userMessagesUnread" count={count}>
|
|
|
Hello <strong title={t('nameTitle')}>{{name}}</strong>, you have {{count}} unread message. <Link to="/msgs">Go to messages</Link>.
|
|
|
</Trans>**
|
|
|
);
|
|
|
}
|
|
|
|
|
|
// Stored translation:
|
|
|
// "userMessagesUnread": "Hello <1>{{name}}</1>, you have {{count}} unread message. <5>Go to message</5>.",
|
|
|
// "userMessagesUnread_plural": "Hello <1>{{name}}</1>, you have {{count}} unread messages. <5>Go to messages</5>."
|
|
|
|
|
|
The numbers in the translation string refer to the specific node's index inside the node tree (see documentation)
|
|
|
|
|
|
**Documentation**: [https://react.i18next.com/latest/trans-component](https://react.i18next.com/latest/trans-component) |
|
|
\ No newline at end of file |