How to integrate i18next in a app written with ionic-react in ionic version 7

105 Views Asked by At

I would like to integrate i18next in my ionic-react app. But I can’t cope with it. My ionic version is 7.

1

There are 1 best solutions below

0
On
  1. Install packages
npm install i18next react-i18next
  1. Create folders and translationfiles, for example
scr/translations/en/global.json
  1. Fill the translationsfiles, for example
{
  "header": {
    "text": "Welcome",
    "text2": "Welcome2"
    }
}
  1. In index.tsx or main.tsx import the translationsfiles and do imports and functions like this:
import global_en from "./translations/en/global.json";
import global_de from "./translations/de/global.json";
import i18next from "i18next";
import { I18nextProvider } from "react-i18next";

i18next.init({
  interpolation: { escapeValue: false },
  lng: "de",
  resources: {
    en: {
      global: global_en,
    },
    de: {
      global: global_de,
    },
  },
});

and in the EventListener do surroundings with

<I18nextProvider i18n={i18next}>
<App />
</I18nextProvider>
  1. Now you can use your translations in other pages, for example in App.tsx
import { useTranslation, initReactI18next } from 'react-i18next';

and in the const App...

const [t, i18n] = useTranslation("global");

const handleChangeLanguage = (lang: string) => {
  i18n.changeLanguage(lang);
};

return...

<h1>{t('header.text')}</h1>