3

I'm having issues figuring out how to lazy load my translations with i18next.

Here's my setup:

i18n
  .use(Backend)
  .use(LanguageDetector)
  .use(initReactI18next)
  .init({
    debug: NODE_ENV === 'development',
    defaultNS: 'translation',
    fallbackLng: false,
    fallbackNS: 'translation',
    keySeparator: false,
    lng: 'en',
    load: 'currentOnly',
    nsSeparator: '.'
  });

I have a folder structure like this:

├── src
│   └── pages
│       ├── customer
│       │   └── home.tsx
│       └── manager
│           └── dashboard.tsx

I keep my translations in /public/locales/en/translation.json and this works fine. However, my app is expanding and I don't want to keep all my translations for a language in single file. E.g. the customer doesn't need to download all the translations for things happening on the manager portal.

My goal is to download translations specifically for the manager's Dashboard.

I've tried creating a file and adding it to this location

/public/locales/en/manager/dashboard

And then in my React component I make use of the following hook:

...
  // This probably needs to change
  const { t } = useTranslation('manager.dashboard');

  return <div>{t('Hello World')}</div>

And just to test it out my /public/locales/en/manager/dashboard.json (I really want to maintain this file structure) file has a single key value in it:

{ "Hello World": "Goodbye World" }

It's not working (works if I add this key to the /public/locales/en/translation.json file)

How can I change my configuration to get this organized nest translation file structure to work.

Barry Michael Doyle
  • 9,333
  • 30
  • 83
  • 143

2 Answers2

3

If you're using useTranslation like that:

const { t } = useTranslation('manager.dashboard');

Your filename should be like this /public/locales/en/manager.dashboard.json

btw. when lazy loading make sure you use Suspense or check for the ready flag: https://react.i18next.com/latest/usetranslation-hook#not-using-suspense

You may also check out this page, regarding multiple translation files: https://react.i18next.com/guides/multiple-translation-files

edit: Alternatively, you can try with this:

const { t } = useTranslation('manager/dashboard');

like here: https://codesandbox.io/s/react-i18next-http-example-forked-2ptmu?file=/src/app.js:153-162

adrai
  • 2,495
  • 1
  • 15
  • 18
1

As an option to an @adrai answer, if you don't want to disable escapeValue options in the i18n configuration, you can use double backslash in the hook:

const { t } = useTranslation('common\\header');

My folder structure is:

├── public
│   └── assets
│       └── locales
│           ├── common
│           |   └── header
│           │       ├── en.json
|           |       └── ua.json
│           └─ login
│              ├── en.json
|              └── ua.json

And in config I have this setting:

backend: {
  loadPath: '/assets/locales/{{ns}}/{{lng}}.json'
},
Vaidual
  • 13
  • 3