React-i18next Trans component explained

Isaías Chávez
April 2021
3 min read

Summary

I had to work with the Trans component from react-i18next, and I realized no one clearly explains how it behaves internally. So I decided to break it down myself. Trans simply walks through my JSX, assigns indexes every time it finds an element, and expects my translation file to mirror that structure. Once both match, it rebuilds the sentence combining text and components. Understanding this made it much easier for me to use Trans when I need translations that include styled or dynamic React elements.

I recently needed to use the Trans component from react-i18next, and the documentation opens with this line:

While the Trans component lets you interpolate or translate complex React elements, the reality is that in most cases you won't actually need it.

After that, the documentation jumps into tiny details but never really explains the internal logic. Everything else I found online felt the same. Nobody clearly describes what Trans is doing behind the scenes.

The 30 second pitch

Here's a quick example. Forget about the Trans tag for a moment. I have a phrase where only the user's email needs to be bold:

<Trans i18nKey="webOnboarding.signInInstruction3">
  Enter your email address <span className="font-bold">{{ email }}</span> and password
</Trans>

Trans works in a very straightforward way. It starts counting from 0, walks through the JSX, and every time it hits a React element, it assigns an index. When the element ends, it increases the index again.

The string ends up looking like this:

<0>Enter your email address </0><1>{{ email }}</1><2> and password</2>

And my translation entry mirrors that structure:

"signInInstruction3": "Enter your email address <1>{{email}}</1> and password"

With both sides aligned, Trans knows exactly where to place the JSX elements inside the final translated output.