3
votes

I am using React-i18next library and I need to get a translation function t() inside of a function.

export function translateCell(cell) {
  const { t } = useTranslation();
  return (t(cell));
}

When using useTranslation() it fails with error

Hooks can only be called inside the body of a function component.

I tried to use I18nextProvider and also .use(initReactI18next) in initialization, but both setups produces same error.

Am I using it the wrong way, or have I misunderstood something?

EDIT: I found out, that only functions, that will be rendered as component can use useTranslation. Like

function export MyComponent (cell) {
  const { t } = useTranslation();
  return (<div>{t(cell)}</div>);
}
...
render(){
<MyComponent/>
2
you should find a solution here stackoverflow.com/questions/53028117/… - samb102
@samb102 I am not using react-hot-loader, which is mentioned in that post. And even when I added it to my project, it did not solved anything :-/ - Michal Červenka
did u try updating react-dom ? - samb102
Sure, my versions are latest: "react": "^16.8.4", "react-dom": "^16.8.4", "react-i18next": "^10.3.0", "react-router-dom": "^4.3.1", "react-scripts": "^2.1.8" - Michal Červenka

2 Answers

3
votes

I found solution in exporting i18n object after inicialization and use that at all other places which I need.

file i18nSetup.js:

i18n
    .use(initReactI18next)
    .init({
        resources: translationResources,
        interpolation: {
            escapeValue: false 
        }
    });

export default i18n;

In other files:

import i18n from "../functions/i18nSetup";

export function translateCell(cell) {
  return (i18n.t(cell));
}
0
votes

Try like this:

import { Trans } from 'react-i18next';

and use it like this:

<Trans>word-key</Trans>

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