Translating strings containing html with react-i18next

We do a lot of React and a lot of translating.

Our library of choice for internationalization is react-i18next.

Recently we faced a challenge – we needed to render a text with dynamic text inside (based on local variables) but also needed some extra formatting – like a bold text of these specific values.

When translating a string that uses a local js variable, one will use the template literals provided. In our case, we needed to render additional HTML that wraps these literals.

Of course, one could just split the text into parts, but in longer paragraphs, it will be hard for the translator to figure out what is the meaning of the text.

As an example, “The isotope <strong>{{ isotopeName }}</strong> is not configured for <strong>{{deviceName}}</strong>” would result in

  • “The isotope”
  • /* render the strong isotope name */
  • “is not configured for “
  • /* Render the strong device name */
  • . // Render the frickin dot!

The better solution would be to use the `Trans` component:

<Trans
    i18nKey={'myKey'}
    default="The isotope <strong>{{ isotopeName }}</strong> is not configured for <strong>{{deviceName}}</strong>."
    values={ isotopeName, deviceName }
    components={{ strong: <strong /> }}
/>

The components prop instructs how to replace the HTML tags from the string during rendering.

The default value is also added as a value for the myKey in the translation file so that the translator can be fully aware of the context of the translated string.

Voilà!

Note to anybody working with i18n – always put yourself in the shoes of the translator.


Comments

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.