Tutorial of using react-i18next
alongside with documentations can be found here.
When first encounter Trans component
, there are many questions: "what are these indexed tags?", "how to get numbers correctly?", "when actually we need to use this component?". Let's dive in.
Table of contents
When to use
Trans component
allows to translate whole JSX tree in one translation: so when the element contains multiple tags and we don't want to break it to small pieces of translation, we can refer to this component.
Indexed tags
Let's say we want output like this:
//MyComponent.jsx
const name='mary';
export default function MyComponent () {
const [state, setState] = useState(1);
return (
<Trans i18nKey="userGreetings" count={state}>
Hello, <strong title={t('nameTitle')}>{{name}}</strong>! You have chosen {{state}} products. <a href="/cart">Go to shopping cart</a>.
</Trans>
)
}
Now, we have to add this string to translation. However, first we need to know what to put instead of html tags. There are several ways to know these numbers:
debug=true and console
The easiest way is to look in console for missing key output (for this to work debug: true
must be in i18n.init({})
options):
And we can just copy that string and paste it in translation:
//translationEn.js
const translation = {
nameTitle: "Your name",
userGreetings: "Hello, <1>{{name}}</1>! You have chosen {{count}} product. <5>Go to shopping cart</5>."
}
export default translation;
React Developer Tools
We can inspect <Trans>
component in devtools:
Here, we have indexes for each child in
props.children
array.
Understand how indexes are generated
Children are divided by these rules:
- plain string;
- object, that's used for interpolation;
- element with its' own children. The children support the same rules. Thus, there can be nested elements in one
Trans component
.
Let's look at our example:
From this string:
Hello, <strong title={t('nameTitle')}>{{name}}</strong>! You have chosen {{state}} products. <a href="/cart">Go to shopping cart</a>.
Children of Trans node:
- 'Hello' - just string;
-
strong
element with a child-object: {name: 'mary'} - 'You have chosen' - just string;
- {state} - object;
- ' products. ' - just string
-
a
element with a child-string:'Go to shopping cart'
- '.' - just string
We come to this:
Hello, <1>{{name}}</1>! You have chosen {{count}} product. <5>Go to shopping cart</5>.
Plurals
We can actually set our translation like this:
userGreetings_one: "Hello, <1>{{name}}</1>! you have chosen {{count}} product. <5>Go to shopping cart</5>.",
userGreetings_other: "Hello, <1>{{name}}</1>! you have chosen {{count}} products. <5>Go to shopping cart</5>."
The difference is in plural form of
product
.
We need prop count
in Trans component
:
<Trans i18nKey="userGreetings" count={state}>...