3

I have a constant that just export data.

Import i18n from './i18n'
export const offersList = [
  {
    id: 0,
    itemButton: i18n.t('item1'),
    title: i18n.t('title1'),
  },
  {
    id: 0,
    itemButton: 'Item 1',
    title: 'Title 1',
  },
  {
    id: 0,
    itemButton: 'Item 1',
    title: 'Title 1',
  }
];

And when I am trying to use t function inside of key it just return a simple string with key what I want to show. And I have i18n.ts file like this

import i18n from 'i18next';
import { initReactI18next } from 'react-i18next';

import Backend from 'i18next-http-backend';

i18n
  .use(Backend)
  .use(initReactI18next)
  .init({
    fallbackLng: 'ru',
    debug: true,
    react: {
      useSuspense: false
    },
    interpolation: {
      escapeValue: false, 
    }
  });


export default i18n;
fristyr
  • 159
  • 1
  • 9

2 Answers2

0

So I found a solution, it is working in my case, but maybe you have the same.

Problem was that I used backend module from i18next

import Backend from 'i18next-http-backend'

In my case, I should not use this module. So i18n.js( or .ts in my case ) configuration file will be like this

import i18n from 'i18next';
import { initReactI18next } from 'react-i18next';

// the translations
// (tip move them in a JSON file and import them)
const resources = {
  en: {
    translation: {
      'title': 'En test title',
    },
  },
  ru: {
    translation: {
      'title': 'Ru test title',
    },
  }
};

i18n
  .use(initReactI18next) // passes i18n down to react-i18next
  .init({
    resources,
    lng: 'en',

    keySeparator: false, // we do not use keys in form messages.welcome

    interpolation: {
      escapeValue: false, // react already safes from xss
    },
  });

export default i18n;

And if you want to work with data outside of component in a simple js/ts file you can use t() function. You should import your i18next configuration file in your file ( in my case a simple array of objects with data which I export )

import i18n from '../../i18n';
const offersList = [ 
  {title: i18n.t('title')},
  {text:  i18n.t('text')},
  {subtitle: i18n.t('subtitle')},
]

// keep in mind, if you want to change the language with a click in-app, you should keep i18n.on a function to fire update what language was changed.

i18n.on('languageChanged', (language) => {
  offersList[0].itemButton = i18n.t('title');
});

export default offersList;
fristyr
  • 159
  • 1
  • 9
0

Try to refactor your simple ts file to a react hook, and call useTranslation() from within the hook. Should work.

Charles Zhao
  • 158
  • 11