9

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 !

3 Answers 3

21

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!!!

Sign up to request clarification or add additional context in comments.

Comments

6

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)

1 Comment

Thank you. This was exactly what I was looking for. Simple and easy.
3

if you have already initialized i18next somewhere, you may use i18next like this:

import { t } from "i18next";

const InYourComponent = () => {
    t('key')
}

const outside_of_components = () => {
    t('key')
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.