React native & react-i18next setup Typescript

This post is a tutorial for setting up react-i18next in React Native with Typescript

Install the required packages

yarn add i18next react-i18next react-native-localize
npm install --save i18next react-i18next react-native-localize

react-native-localize we need to detect the device language

Setup in project

  • In the root off your React Native project add a folder "translations"
  • Now create a new Typescript file in this folder called "i18n.ts"
import i18n from 'i18next';
import {initReactI18next} from 'react-i18next';
import {getLocales} from 'react-native-localize';

import EN from './en.json';

i18n.use(initReactI18next).init({
  resources: {
    en: {translation: EN},
  },
  lng: getLocales()[0].languageCode, // Get the first device language
  fallbackLng: 'en',
  compatibilityJSON: 'v3', // By default React Native projects does not support Intl
});

export default i18n;
  • Add a JSON file in the same folder called "en.json"
{
  "TITLE": "React Native",
}
  • Import the i18n.ts file in your App.tsx to initialise the setup
import './translations/i18n';

Now you all done! You can start using i18next functionality in your entire project.

Hinting Typescript (optional)

You can have hinting tips for your translations keys so you don't use a key that doesn't exist.

  • Create Typescript file called "react-18next.d.t"
import EN from './en.json';

declare module 'react-i18next' {
  interface CustomTypeOptions {
    defaultNS: 'en';
    resources: {
      en: typeof EN;
    };
  }
}

73