Joel Nordström
Joel Nordström

Reputation: 81

How to use the react-i18next <Trans> component properly

In their examples on github, and in other places, react-i18next seem to suggest that we should use their Trans component by filling it with some kind of text, which to my understanding does not appear in the resulting app in any way since it gets overwritten by the default locale. What's it for? Is it just there to make sure react doesn't optimize away the components?

Upvotes: 4

Views: 3027

Answers (3)

Rekss
Rekss

Reputation: 41

There is a text that needs to be translated:

<p>Please enter the <strong>IP-address</strong> and <strong>port</strong> of the KNX gateway</p>

In the translation file for the English language, we add a translation option, where the numbers in the tags are the serial numbers of the text segments separated by these tags.

"KNX_ip_and_port": "Please enter the <1>IP address</1> and <3>port</3> of the KNX gateway"

We do the same with a translation file, for example Russian.

"KNX_ip_and_port": "Пожалуйста, введите <1>IP-адрес</1> и <3>порт</3> шлюза KNX"

And finally, we replace the content of the paragraph with a trans component with serial numbers instead of the original text.

<p>
    <Trans i18nKey="KNX_ip_and_port">
        0<strong>1</strong>2<strong>2</strong>4
    </Trans>
</p>

Upvotes: 0

Aleksi
Aleksi

Reputation: 5036

An old question, but this fantastic resource here really helped me wrap my head around the <Trans /> component.

Upvotes: 5

Joel Nordstr&#246;m
Joel Nordstr&#246;m

Reputation: 81

So after doing some more research, and trying a few suggestions, it seems that the recommended way to use <Trans> is to use the default text as a key in your autogenerated translation files, so

<Trans>Lorem ipsum</Trans>

in your code would give you

{"Lorem ipsum": "Lorem ipsum"}

in your default locale file, which could then be translated like

{"Lorem ipsum": "Löksås yxskaft"}

Upvotes: 2

Related Questions