Ask Your Question
3

How can we integrate react-i18next in a NX Monorepo?

asked 2022-02-26 11:00:00 +0000

plato gravatar image

edit retag flag offensive close merge delete

1 Answer

Sort by ยป oldest newest most voted
3

answered 2023-04-06 18:00:00 +0000

djk gravatar image

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.

edit flag offensive delete link more

Your Answer

Please start posting anonymously - your entry will be published after you log in or create a new account. This space is reserved only for answers. If you would like to engage in a discussion, please instead post a comment under the question or an answer that you would like to discuss

Add Answer


Question Tools

Stats

Asked: 2022-02-26 11:00:00 +0000

Seen: 10 times

Last updated: Apr 06 '23