Trans Component

Important note

While <Trans> gives you a lot of power by letting you interpolate or translate complex React elements, the truth is: in most cases you don't even need it.
As long you have no React/HTML nodes integrated into a cohesive sentence (text formatting like strong, em, link components, maybe others), you won't need it - most of the times you will be using the good old t function.
You may be looking directly for the Trans props.
It does ONLY interpolation. It does not rerender on language change or load any translations needed. Check useTranslation hook or withTranslation HOC for those cases.
1
import React from 'react';
2
import { Trans, useTranslation } from 'react-i18next'
3
4
function MyComponent() {
5
const { t } = useTranslation('myNamespace');
6
7
return <Trans t={t}>Hello World</Trans>;
8
}
Copied!
Have a look at the i18next documentation for details on the the t function:

Samples

Using with React components

So you learned there is no need to use the Trans component everywhere (the plain t function will just do fine in most cases).
This component enables you to nest any React content to be translated as one cohesive string. It supports both plural and interpolation.
Let's say you want to create following HTML output:
Hello Arthur, you have 42 unread messages. Go to messages.
Before: Your untranslated React code would have looked something like:
1
function MyComponent({ person, messages }) {
2
const { name } = person;
3
const count = messages.length;
4
5
return (
6
<>
7
Hello <strong title="This is your name">{name}</strong>, you have {count} unread message(s). <Link to="/msgs">Go to messages</Link>.
8
</>
9
);
10
}
Copied!
After: With the Trans component just change it to:
1
import { Trans } from 'react-i18next';
2
3
function MyComponent({ person, messages }) {
4
const { name } = person;
5
const count = messages.length;
6
7
return (
8
<Trans i18nKey="userMessagesUnread" count={count}>
9
Hello <strong title={t('nameTitle')}>{{name}}</strong>, you have {{count}} unread message. <Link to="/msgs">Go to messages</Link>.
10
</Trans>
11
);
12
}
Copied!
Your en.json (translation strings) will look like:
1
"nameTitle": "This is your name",
2
"userMessagesUnread_one": "Hello <1>{{name}}</1>, you have {{count}} unread message. <5>Go to message</5>.",
3
"userMessagesUnread_other": "Hello <1>{{name}}</1>, you have {{count}} unread messages. <5>Go to messages</5>.",
Copied!
saveMissing will send a valid defaultValue based on the component children. Also, The i18nKey is optional, in case you already use text as translation keys.

Alternative usage which lists the components (v11.6.0)

1
<Trans
2
i18nKey="myKey" // optional -> fallbacks to defaults if not provided
3
defaults="hello <italic>beautiful</italic> <bold>{{what}}</bold>" // optional defaultValue
4
values={{ what: 'world'}}
5
components={{ italic: <i />, bold: <strong /> }}
6
/>
Copied!
This format is useful if you want to interpolate the same node multiple times. Another advantage is the simpler named tags, which avoids the trouble with index guessing - however, this can also be achieved with transSupportBasicHtmlNodes, see the next section.
Existing self-closing HTML tag names are reserved keys and won't work. Examples: link: <Link />, img: <img src="" />, media: <img src="" />

Usage with simple HTML elements like <br /> and others (v10.4.0)

There are two options that allow you to have basic HTML tags inside your translations, instead of numeric indexes. However, this only works for elements without additional attributes (like className), having none or a single text children.
Examples of elements that will be readable in translation strings:
  • <br/>
  • <strong>bold</strong>
  • <p>some paragraph</p>
Examples that will be converted to indexed nodes:
  • <i className="icon-gear" />: no attributes allowed
  • <strong title="something">{{name}}</strong>: only text nodes allowed
  • <b>bold <i>italic</i></b>: no nested elements, even simple ones
1
<Trans i18nKey="welcomeUser">
2
Hello <strong>{{name}}</strong>. <Link to="/inbox">See my profile</Link>
3
</Trans>
4
// JSON -> "welcomeUser": "Hello <strong>{{name}}</strong>. <1>See my profile</1>"
5
6
<Trans i18nKey="multiline">
7
Some newlines <br/> would be <br/> fine
8
</Trans>
9
// JSON -> "multiline": "Some newlines <br/> would be <br/> fine"
Copied!
Here is what can be configured in i18next.options.react that affect this behaviour:
Option
Default
Description
transSupportBasicHtmlNodes
true
Enables keeping the name of simple nodes (e.g. <br/>) in translations instead of indexed keys
transKeepBasicHtmlNodesFor
['br', 'strong', 'i', 'p']
Which nodes are allowed to be kept in translations during defaultValue generation of <Trans>.
transWrapTextNodes (v11.10.0)
''
Wrap text nodes in a user-specified element. e.g. set it to span. By default, text nodes are not wrapped. Can be used to work around a well-known Google Translate issue with React apps. See facebook/react#11538.

Interpolation

You can pass in variables to get interpolated into the translation string by using objects containing those key:values.
1
const person = { name: 'Henry', age: 21 };
2
const { name, age } = person;
3
4
<Trans>
5
Hello {{ name }}. // <- = {{ "name": name }}
6
</Trans>
7
// Translation string: "Hello {{name}}"
8
9
10
<Trans>
11
Hello {{ firstname: person.name }}.
12
</Trans>
13
// Translation string: "Hello {{firstname}}"
Copied!

Plural

You will need to pass the count prop:
1
const messages = ['message one', 'message two'];
2
3
<Trans i18nKey="newMessages" count={messages.length}>
4
You got {{ count: messages.length }} messages.
5
</Trans>
6
7
// Translation strings:
8
// "newMessages": "You got one message."
9
// "newMessages_plural": "You got {{count}} messages."
Copied!

Using with lists (v10.5.0)

You can still use Array.map() to turn dynamic content into nodes, using an extra option on a wrapping element:
1
<Trans i18nKey="list_map">
2
My dogs are named:
3
<ul i18nIsDynamicList>
4
{['rupert', 'max'].map(dog => (<li>{dog}</li>))}
5
</ul>
6
</Trans>
7
// JSON -> "list_map": "My dogs are named: <1></1>"
Copied!
Setting i18nIsDynamicList on the parent element will assert the nodeToString function creating the string for saveMissing will not contain children.

Alternative usage (components array)

Some use cases, such as the ICU format, might be simpler by just passing content as props:
1
<Trans
2
i18nKey="myKey" // optional -> fallbacks to defaults if not provided
3
defaults="hello <0>{{what}}</0>" // optional defaultValue
4
values={{ what: 'world'}}
5
components={[<strong>univers</strong>]}
6
/>
Copied!
<0> -> 0 is the index of the component in the components array
E.g. this format is needed when using ICU as translation format as it is not possible to have the needed syntax as children (invalid jsx).

How to get the correct translation string?

Guessing replacement tags (<0></0>) of your component is rather difficult. There are four options to get those translations directly generated by i18next:
  1. 1.
    use React Developer Tools to inspect the <Trans> component instance and look at the props.children array for array index of the tag in question.
  2. 2.
    use debug = true in i18next.init() options and watch your console for the missing key output
  3. 3.
    use the saveMissing feature of i18next to get those translations pushed to your backend or handled by a custom function.
  4. 4.
    understand how those numbers get generated from child index:
Sample JSX:
1
<Trans i18nKey="userMessagesUnread" count={count}>
2
Hello <strong title={t('nameTitle')}>{{name}}</strong>, you have {{count}} unread message. <Link to="/msgs">Go to messages</Link>.
3
</Trans>
Copied!
Resulting translation string:
1
"Hello <1>{{name}}</1>, you have {{count}} unread message. <5>Go to message</5>."
Copied!
The complete the node tree:
1
Trans.children = [
2
'Hello ', // 0: only a string
3
{ children: [{ name: 'Jan' }] }, // 1: <strong> with child object for interpolation
4
', you have ', // 2: only a string
5
{ count: 10 }, // 3: plain object for interpolation
6
' unread messages. ', // 4: only a string
7
{ children: ['Go to messages'] }, // 5: <Link> with a string child
8
'.' // 6: yep, you guessed: another string
9
]
Copied!
Rules:
  • child is a string: nothing to wrap; just take the string
  • child is an object: nothing to do; it's used for interpolation
  • child is an element: wrap it's children in <x></x> where x is the index of that element's position in the children list; handle its children with the same rules (starting element.children index at 0 again)

Trans props

All properties are optional, although you'll need to use i18nKey if you're not using natural language keys (text-based).
name
type (default)
description
i18nKey
string (undefined)
If you prefer to use text as keys you can omit this, and the translation will be used as key. Can contain the namespace by prepending it in the form 'ns:key' (depending on i18next.options.nsSeparator)
But this is not recommended when used in combination with natural language keys, better use the dedicated ns parameter: <Trans i18nKey="myKey" ns="myNS"></Trans>
ns
string (undefined)
Namespace to use. May also be embedded in i18nKey but not recommended when used in combination with natural language keys, see above.
t
function (undefined)
t function to use instead of i18next.t()
count
integer (undefined)
Numeric value for pluralizable strings
tOptions
object (undefined)
Extra options to pass to t() (e.g. context, postProcessor, ...)
parent
node (undefined)
A component to wrap the content into (can be globally set on i18next.init). Required for React < v16
i18n
object (undefined)
i18next instance to use if not provided
defaults
string (undefined)
Use this instead of using the children as default translation value (useful for ICU)
values
object (undefined)
Interpolation values if not provided in children
components
array[nodes] (undefined)
Components to interpolate based on index of tag

i18next options

1
i18next.init({
2
// ...
3
react: {
4
// ...
5
hashTransKey: function(defaultValue) {
6
// return a key based on defaultValue or if you prefer to just remind you should set a key return false and throw an error
7
},
8
defaultTransParent: 'div', // a valid react element - required before react 16
9
transEmptyNodeValue: '', // what to return for empty Trans
10
transSupportBasicHtmlNodes: true, // allow <br/> and simple html elements in translations
11
transKeepBasicHtmlNodesFor: ['br', 'strong', 'i'], // don't convert to <1></1> if simple react elements
12
transWrapTextNodes: '', // Wrap text nodes in a user-specified element.
13
// i.e. set it to 'span'. By default, text nodes are not wrapped.
14
// Can be used to work around a well-known Google Translate issue with React apps. See: https://github.com/facebook/react/issues/11538
15
// (v11.10.0)
16
}
17
});
Copied!
Please be aware if you are using React 15 or below, you are required to set the defaultTransParent option, or pass a parent via props.
Are you having trouble when your website is ran through Google Translate? Google Translate seems to manipulate the DOM and makes React quite unhappy! There's a work around: you can wrap text nodes with<span> using transWrapTextNodes: 'span'.
If you want to know more about the Google Translate issue with React, have a look at this.
Last modified 12d ago