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

3

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 !

Frijol answered 10/9, 2019 at 4:29 Comment(0)
L
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!!!

Lindie answered 10/9, 2019 at 5:21 Comment(0)
G
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)
Guttering answered 5/6, 2020 at 10:5 Comment(1)
Thank you. This was exactly what I was looking for. Simple and easy.Spiral
P
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')
}
Perchance answered 29/3, 2023 at 17:36 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.