How can I translate object array in React through i18n?

I have a problem about change the language in the object array in React through i18n.

I cannot react "t" feature of useTranslation. That's why I got an issue.

Here is my object array shown below.

import { useTranslation } from 'react-i18next';

export const CARD_DATA = [
  {
    'title': useTranslation.t('Card Data Title'), -> ERROR
    'icon': faCircleUser,
    'details': "I've studied Typography & Graphic Communication \
                at possibly the best Institution to do so in the \
                world - The University of Reading.",
    'color': '#e75d5d'
  },
  {
    'title': 'Responsive Web Design',
    'icon': faHeadphonesAlt,
    'details': 'I design future proof mobile first reponsive websites \
                to the latest web standards. I also keep up with \
                the most recent best practices.',
    'color': '#e75d5d'
  }
]

Here is my Home Page.

import { CARD_DATA } from '../data/CardData';

<div className={styles.cardGrid}>
    <CardGridView data={ CARD_DATA } />
</div>

Here is my i18n component shown below.

i18n.use(initReactI18next).init({
    resources: {
      en: {
        translations: {
          'Card Data Title' : 'English'
        }
      },
      de: {
        translations: {
           'Card Data Title' : 'Deutsch'
        }
      }
    },
    fallbackLng: 'tr',
    ns: ['translations'],
    defaultNS: 'translations',
    keySeparator: false,
    interpolation: {
      escapeValue: false,
      formatSeparator: ','
    },
    react: {
      wait: true
    }
  });
  
export default i18n;

How can I fix my issue?

Upvotes: 2

Views: 5062

Answers (1)

adrai
adrai

Reputation: 3168

https://react.i18next.com/guides/quick-start

If you need to access the t function or the i18next instance from outside of a React component you can simply import your ./i18n.js and use the exported i18next instance:

import i18next from './i18n'

i18next.t('my.key')

i18next docs

You may want to also listen to the languageChanged event to reset the appropriate translation, i.e.

i18next.on('languageChanged', (lng) {
  i18next.t('my.key')
})

Upvotes: 6

Related Questions