Search code examples
reactjsreact-nativeinternationalizationreact-i18next

react-native not showing translated text


I have the following tree structure

❯ tree src/localization 
src/localization
├── en
│   └── index.ts
├── i18n.ts
└── ta
    └── index.ts

and the following i18n.ts file contents

❯ cat src/localization/i18n.ts 
import i18n from "i18next";
import { initReactI18next } from "react-i18next";
import en from "./en/index";
import ta from "./ta/index";

const resources = {
  // list of languages
  en,
  ta,
};

i18n.use(initReactI18next).init({
  compatibilityJSON: "v3",
  resources,
  lng: "ta", // default language to use.
  interpolation: {
    escapeValue: false,
  },
});

export default i18n;

And I include this i18n.ts in my App.tsx as below:

❯ cat App.tsx 
import { AuthProvider } from "./src/context/AuthContext";
import { AppNav } from "./src/context/AppNav";
import "./src/localization/i18n";

function App() {
  return (
    <AuthProvider>
      <AppNav />
    </AuthProvider>
  );
}

export default App;

Now I try to use a translation from the above file in a react-native screen, like below:

import { useTranslation } from "react-i18next";
const { t } = useTranslation();
<Text> {t("sign_in")} </Text>

In the ta/index.ts and the en/index.ts I have no namespace and have translated strings. But in the npm run web on the browser, the sign_in text appears as is, instead of the translated string from the localization directory. I tried changing the default language to en also and set a different value for the sign_in key and even that does not help. The content of ta/index.ts is as below:

export default {
  account_handle: "பயனர் கணக்கு",
  change_language: "Change Language",
  forgot_password: "கடவுச்சொல் மறந்ததோ",
  password: "கடவுச்சொல்",
  sign_in: "உள்ளே போ",
};

The entire react-native project is available at: https://github.com/psankar/immiapp/tree/e87ca8a9b4de764608da96d2945120383f50ed70

The react-component where I am trying to use the translated string is: https://github.com/psankar/immiapp/blob/e87ca8a9b4de764608da96d2945120383f50ed70/src/screens/SignIn.tsx#L114

What am I doing wrong that the translated strings are not appearing in the UI ?


Solution

  • Had to make changes to the i18n.ts as below by adding a translation key:

    i18n.use(initReactI18next).init({
      compatibilityJSON: "v3",
      resources: {
        en: {
          translation: en,
        },
        ta: {
          translation: ta,
        },
      },
      lng: "ta", // default language to use.
      interpolation: {
        escapeValue: false,
      },
    });
    

    and in the SignIn.tsx, had to import the t function via the above file, such as:

    import i18n from "../localization/i18n";
    <Text>{i18n.t("sign_in")}</Text>