Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use react-i18next inside BASIC function (not component)?

I know that react-i18next work in every component: functional (with useTranslation) and class component (with withTranslation()) BUT I can't use translation inside a basic function like this:

const not_a_component = () => {
  const { t } = useTranslation();
  return t('translation')
};

const translate = not_a_component();

ERROR HOOKS !

Thanks !

like image 815
Theo Cerutti Avatar asked May 06 '26 23:05

Theo Cerutti


2 Answers

You could just use i18next library for translation using javascript. react-i18next is just a wrapper library on top of i18next.

Below is an example if you are already using react-i18next and it is configured.

import i18next from "i18next";

const not_a_component = () => {
  const result = i18next.t("key");
  console.log(result);
  return result;
};

export default not_a_component;

If you opt to use only i18nextthen you could simply get t function. It all depends upon your requirement.

import i18next from 'i18next';

i18next.init({
  lng: 'en',
  debug: true,
  resources: {
    en: {
      translation: {
        "key": "hello world"
      }
    }
  }
}, function(err, t) {
  // You get the `t` function here.
  document.getElementById('output').innerHTML = i18next.t('key');
});

Hope that helps!!!

like image 67
tarzen chugh Avatar answered May 09 '26 23:05

tarzen chugh


Alternatively, you can pass t as an additional parameter:

const not_a_component = (t) => {
  return t('translation')
};

// Within a component
const { t } = useTranslation()
not_a_component(t)
like image 40
weakish Avatar answered May 10 '26 01:05

weakish