i18next with HttpBackend, Trans looking for key before init finished

427 Views Asked by At

I'm loading translations dynamically, with the HttpBackend However inside my component I use the Trans component, and it is screaming about missing translation key, I also see the init finished after it tried to access the Trans component. I have a Suspens around my app, why is this happens?

I get in the console: i18next::translator: missingKey en translation myKey This is text that has a
in it....  the init happens after.

How can I fix this?

// file: i18n.js
i18n
  // load translation using http -> see /public/locales (i.e. https://github.com/i18next/react-i18next/tree/master/example/react/public/locales)
  // learn more: https://github.com/i18next/i18next-http-backend
  .use(Backend)
  // detect user language
  // learn more: https://github.com/i18next/i18next-browser-languageDetector
  // pass the i18n instance to react-i18next.
  .use(initReactI18next)
  // init i18next
  // for all options read: https://www.i18next.com/overview/configuration-options
  .init({
    fallbackLng: 'en',
    debug: true,
    supportedLngs: ['en', 'bg', 'rs'],
    interpolation: {
      escapeValue: false, // not needed for react as it escapes by default
    },
    backend: {
      loadPath: '/static/{{lng}}.translations.json',
    },
    react: {
      wait: true,
      useSuspense: true,
    },
    transSupportBasicHtmlNodes: true,
  });

export default i18n;

// app.js
function App() {
  return (
    <BrowserRouter>
      <Apollo>
        <Suspense fallback={<Loading />}>
          <ThemeProvider theme={theme}>
            <Header />
            <Routes />
            <Footer />
          </ThemeProvider>
        </Suspense>
      </Apollo>
    </BrowserRouter>
  );
}

problematic component:

//home
const I18N_TEXT_KEY_CONSTANT = 'text_key';
const Home = () => (
  <Trans i18nKey={I18N_TEXT_KEY_CONSTANT}>
    This is text that has a <br /> in it and also some random spaces.
  </Trans>
);    
2

There are 2 best solutions below

0
On

The solution which is sadly not document is:

const {t}  = useTranstions()
<Trans i18nKey="someKey" t={t}>

Passing the t into the Trans works perfectly.

0
On

You should pass the t function to Trans component.

//home
import { useTranslation } from 'react-i18next';
const I18N_TEXT_KEY_CONSTANT = 'text_key';

const Home = () => {
  const { t } = useTranslation();
  return (
    <Trans i18nKey={I18N_TEXT_KEY_CONSTANT} t={t}>
      This is text that has a <br /> in it and also some random spaces.
    </Trans>
  );
};