0

I import an object that i have on a constant file in my functional component, but it doesn't get translated according to the selected language.

I guess it's cause of timing, probably the language hasn't been loaded yet.

I cannot change the labels into string for several reason, so i need to understand how to update the i18n according to the language change.

so which is the best way to handle this?

is there a way to wait till the languages is loaded?

export const myTypes: FormSelectOptions = [
  { value: 'alpha', label: i18next.t('alpha.string') },
  { value: 'beta', label: i18next.t('beta.string') },
];

my i18n config

import Backend from 'i18next-xhr-backend';
import i18next from 'i18next';

i18next
  .use(Backend)
  .use(initReactI18next)
  .init({
    backend: {
      loadPath: './translations/{{lng}}.json',
      addPath: './translations/{{lng}}/{{ns}}.missing.json',
      crossDomain: true,
    },
    resources: {
      en: {
        main: require('./translations/en.json'), // eslint-disable-line
      },
      it: {
        main: require('./translations/it.json'), // eslint-disable-line
      },
    },
    lng: 'it',
    defaultNS: 'main',
    saveMissing: false,
    saveMissingTo: 'all',
    fallbackNS: process.env.NODE_ENV === 'development' ? false : 'main',
    fallbackLng: process.env.NODE_ENV === 'development' ? false : 'en',
    debug: process.env.NODE_ENV === 'development',
  });

export default i18next;
```
junray
  • 163
  • 3
  • 15
  • `myTypes` is defined inside of the component? Please provide your i18n configuration. – Filip Seman Feb 03 '21 at 15:44
  • no it's defined outside in a different file and it's imported in the component – junray Feb 03 '21 at 15:55
  • Does this answer your question? [i18next translation outside component](https://stackoverflow.com/questions/57114733/i18next-translation-outside-component) – Filip Seman Feb 03 '21 at 16:15
  • the problem seems the same but the solution wouldn't work in my case – junray Feb 03 '21 at 16:25
  • Add reproducible codesandbox or repository link to the description, so we can debug the problem. – Filip Seman Feb 03 '21 at 16:53
  • You may want to check out the official react-i18next example: https://github.com/i18next/react-i18next/tree/master/example/react – adrai Feb 04 '21 at 13:59

0 Answers0