React Native issue with I18n in an array of object

743 Views Asked by At

I use I18n in my app with a config :

 I18n.translations = {
    en: en,
    fr: fr,
  };

  if (!__DEV__) {
    I18n.fallbacks = true;
  }

  I18n.defaultLocale = 'en';
  I18n.locale = localeLanguageTag as ELanguagesKeys;  

Then I export it and use it as usual ...

In a component, I have an object array with some translation key :

const onBordingSteps: ISteps = [
    {
      label: I18n.t('auth.heading.steps.onboarding.step1.title'),
      isCompleted: true,
      icon: GGValidation,
      iconHeight: 49.36,
      iconWidth: 28.48,
    },
    {
      label: I18n.t('auth.heading.steps.onboarding.step2.title'),
      isCompleted: false,
      .....
  ];

I use this array directly after its creation in my component

return (
    <PreOnboarding
      steps={onBordingSteps}
    ...  

But when I import this array from another file, it didn't find the key and I have this error on each items:

enter image description here
I don't understand why ... an idea?

1

There are 1 best solutions below

2
On

Maybe this will help you, because I think it might be an issue with the export method of the keys since they cannot be found

In my implementation I store the keys like this

  1. I have a js/ts file, called Strings where I store the keys

import { translate } from "./I18n"

const Strings = {
  SOME_WORD: translate("keyName.firstWord"),
  ANOTHER_WORD:  translate("keyName.firstWord")
  ...
 }

  1. In my l18n file I defined a translate function (in this way you won't have to import the i18n-js wherever you use it

import * as RNLocalize from "react-native-localize"
import i18n from "i18n-js"

import en from "./en"

const translations = { en }

const { languageTag } = RNLocalize.findBestAvailableLanguage(Object.keys(translations)) || {
  languageTag: "en",
}

i18n.locale = languageTag
i18n.fallbacks = true
i18n.translations = translations

export function translate(key: string) {
  return key ? i18n.t(key) : ""
}

export default i18n

  1. In a separate file, called en.ts I have the actual translations

export default {
  keyName: {
    firstWord: "The actual translation",
    ...
    
   }
}