Ask Your Question

Revision history [back]

click to hide/show revision 1
initial version

To integrate react-i18next in an NX Monorepo, you can follow these steps:

  1. Create a new library in your monorepo for i18n utilities using the command:
nx g @nrwl/react:library i18n
  1. Install react-i18next and its dependencies using the command:
npm install i18next react-i18next --save
  1. Inside your newly created i18n library, create a new file i18n.ts and import i18next and react-i18next:
import i18n from 'i18next';
import { initReactI18next } from 'react-i18next';
  1. Initialize i18next in the i18n.ts file:
i18n
  .use(initReactI18next) // initialize react i18next
  .init({
    lng: 'en',
    fallbackLng: 'en',
    interpolation: {
      escapeValue: false,
    },
    resources: {},
  });
  1. To add supports for multiple languages, create a directory locales in the i18n library and add subdirectories for each language. Inside each language subdirectory, add a translation.json file that contains key-value pairs for translating text in your app.

  2. In the i18n.ts file, import the translation.json files from the locales directory and add them to the resources object in the init() function:

import enTranslation from './locales/en/translation.json';
import esTranslation from './locales/es/translation.json';

i18n
  .use(initReactI18next)
  .init({
    lng: 'en',
    fallbackLng: 'en',
    interpolation: {
      escapeValue: false,
    },
    resources: {
      en: {
        translation: enTranslation,
      },
      es: {
        translation: esTranslation,
      },
    },
  });
  1. Finally, export the i18n object from the i18n.ts file to make it accessible for use in other parts of your app:
export default i18n;
  1. In your React components, use the useTranslation() hook from react-i18next to access the t() function for translating text:
import { useTranslation } from 'react-i18next';

function MyComponent() {
  const { t } = useTranslation();

  return (
    <div>{t('App title')}</div>
  );
}

That's it! You should now be able to use react-i18next for internationalization in your NX Monorepo.