React i18next useTranslation Hook in helper method
I fixed my issue by not using the useTranslation
hook anymore
Instead I moved the i18n
initalizitation to a file (i18n.tsx - exports i18n
)and import and use it in my Utils class
My Utils.tsx file now looks like this
Utils.tsx
...import i18n from '../i18n';...export function helperFunction(props: any){ //do stuff //use imported i18n and call the t() method i18n.t("needTranslation");}
i18n.tsx
import i18n from "i18next";import Backend from 'i18next-xhr-backend';import { initReactI18next } from 'react-i18next';i18n .use(Backend) .use(initReactI18next) // passes i18n down to react-i18next .init({ lng: "es", fallbackLng: 'en', backend: { loadPath: '/static/locales/{{lng}}/{{ns}}.json' }, interpolation: { escapeValue: false } }); export default i18n;
It looks like you forgot a quote t("needTranslation);
-> t("needTranslation");
After I ran your code I see why your code isn't working. If you want to extract component logic into reusable functions, then you should make a custom hook. For more info look at the docs.
import React from "react";import ReactDOM from "react-dom";import i18n from "i18next";import "./i18n.js";import { useTranslation, initReactI18next } from "react-i18next";i18n .use(initReactI18next) .init({ resources: { en: { translation: { title: "Hello world", subtitle: "Hello stackoverflow" } } }, lng: "en", fallbackLng: "en", interpolation: { escapeValue: false } });function App() { const { t } = useTranslation(); useHelperFunction(); return <h1>{t("title")}</h1>;}// you need to turn the helper function into a hookfunction useHelperFunction() { const { t } = useTranslation(); return <h2>{t("subtitle")}</h2>;}const rootElement = document.getElementById("root");ReactDOM.render(<App />, rootElement);