Add i18next to Internationalize a React Native + Expo APP using TypeScript

Tiempo de lectura: 2 minutos

Today we are going to learn how we can internationalize and add multi-language support to a React Native APP using TypeScript.

The first thing we will do is install i18n:

npm install i18next react-i18next --save

Once installed, we create a folder called language and inside it, we create a file i18next.ts

// i18next.ts
import i18n from 'i18next';
import { initReactI18next } from 'react-i18next';
import { Platform, NativeModules } from 'react-native';
import en from './en.json';
import es from './es.json';

function idioma(): string {
  try {
    const deviceLanguage: string =
      Platform.OS === 'ios'
        ? NativeModules.SettingsManager.settings.AppleLocale 
          NativeModules.SettingsManager.settings.AppleLanguages[0] //iOS 13
        : NativeModules.I18nManager.localeIdentifier;
    var deviceLanguageSplit: string = deviceLanguage.split("_")[0];
    return deviceLanguageSplit;
  } catch (error) {
    var idiomaDevuelve: string = "es"; // Default language
    return idiomaDevuelve; // Default in browser
  }
}

i18n
  .use(initReactI18next)
  .init({
    lng: idioma(),
    fallbackLng: 'en',
    compatibilityJSON: 'v3',
    resources: {
      en: en,
      es: es
    },
    interpolation: {
      escapeValue: false // react already safes from xss
    },
    initImmediate: false, // Add this line
  });

export default i18n;

This file will automatically determine the selected language on the device.

The default language is English (en).

If we want to support more languages, we will add them in resources.

Now we have to create the language files that we are importing.

en.json

{
    "translation": {
      "app_name": "My APP",
     }
}

Inside translation, we have to add the keys that we will use in our APP.

es.json

{
    "translation": {
      "app_name": "Mi Aplicación",
     }
}

*To allow us to read JSON files in imports without error within i18next.ts, we have to add the following in tsconfig.json

"compilerOptions": {
...
    "resolveJsonModule": true,
...

Now we have to import the i18next.ts file into our entry point (usually app.tsx)

import '@/language/i18n';

With this import, i18next will initialize correctly.

To use it, we have to do the following:

  • Import the t variable from useTranslation()
const HomeScreen = () => {
...
  const { t } = useTranslation();
...

And we use it as follows:

      <Text style={styles.title}>{t("app_name")}</Text>

Leave a Comment