4

I have a problem with missing translation even though the translation exits,

const translationGetters = {
  en: () => require('./translations/en.json'),
  de: () => require('./translations/de.json'),
};

const translate = memoize(
  (key, config) => i18n.t(key, config),
  (key, config) => (config ? key + JSON.stringify(config) : key),
);

const setI18nConfig = () => {
  // fallback if no available language fits
  const fallback = {languageTag: 'en', isRTL: false};

  const {languageTag, isRTL} =
    RNLocalize.findBestAvailableLanguage(Object.keys(translationGetters)) ||
    fallback;

  // clear translation cache
  translate.cache.clear();
  // update layout direction
  I18nManager.forceRTL(isRTL);
  // set i18n-js config
  i18n.translations = {[languageTag]: translationGetters[languageTag]()};
  i18n.locale = languageTag;
};

const App = () => {
  handleLocalizationChange = () => {
    setI18nConfig()
      .then(() => this.forceUpdate())
      .catch(error => {
        console.error(error);
      });
  };

  useEffect(() => {
    setI18nConfig();

    RNLocalize.addEventListener('change', handleLocalizationChange);

    return () => {
      RNLocalize.removeEventListener('change', handleLocalizationChange);
    };
  }, []);

  return (
    <ThemeProvider theme={ThemeRed}>
      <AppContainer />
    </ThemeProvider>
  );
};

export default App;

and in HomeScreen

import i18n from 'i18n-js';

const HomeScreen = ({...props}) => {
  return (
    <SafeAreaView style={styles.mainView}>
      <Text style={styles.welcomeText}>{i18n.t('welcome')}</Text>
   </SafeAreaView>
  );
};

export default HomeScreen;

can anyone help to see what I'm doing wrong.

any help would be appreciated.

akano1
  • 40,596
  • 19
  • 54
  • 67

2 Answers2

1

I think in homescreen during translating one has to import the translate function and use {translate('home')} instead of i18n.t() in Homescreen/any screen.

D4rk4rmy
  • 76
  • 2
0

I have answered a quite similar question 2 days ago: How to use setLocale within i18n-js?

I was not using react-native-localize but expo-localization but I don't this is an issue. You are still using i18n-js like I do, so it may apply.

MBach
  • 1,647
  • 16
  • 30