How to Safely Internationalize Your React App

No more missing translations

Krzysztof Kwieciński
Better Programming

--

Photo by Vladislav Klapin on Unsplash.

To reach as many en.users as possible, applications should be internationalized.

Internationalization Library

There are plenty of internationalization libraries to help us with the tedious task of supporting multiple languages. One of them is the i18next library. It offers a lot of features and is well suited for both React and React Native (react-18next).

In the library’s official example, translations are stored in .json files:

Translations in JSON

With such defined translations, we just have to use them in our code. An example invocation looks like this: t('hello'). For a chosen language, the corresponding value is displayed (e.g. either Hello world or Witaj świecie).

However, there is one problem with the example above.

Missing Values

Imagine that we add a new translation to the en-translation.json"dog": "dog". Since most of our users use the English version of the application, no one checks the Polish version for a while.

Then, one day, there is a Pole who wants to use the app. Unfortunately, they cannot fully enjoy the app due to the missing translation for the dog!

Missing pl-translation “dog”: “pies” (Photo by Charles Deluvio on Unsplash)

Depending on how i18next is configured, some other value will be displayed (e.g. a key of the missing value or the value from a fallback language). In both cases, the user experience will fall far below expectations.

TypeScript to the Rescue

Thanks to TypeScript, it is possible to avoid such a poor experience.

The S in TypeScript stands for Superman? (Photo by Elias Castillo on Unsplash)

Firstly, translation files have to be saved as .ts — not .json.

Then we could define an interface with all the needed keys. However, I find it superfluous.

Given that English is our default language option, we can simply define all English translations and then extract a type of the en-translation object.

Finally, we can just use the extracted type as a type for the pl-translation object and let the TypeScript compiler take care of any missing translations!

Translations in TypeScript

Thanks for reading!

--

--

Software Craftsman who loves learning new things and is always eager to share his knowledge with others