6

I followed the react-i18next docs and internationalized my React app.

I use the useTranslation hook, which gives me the "t" object. All nice and smooth for now, but I have some non-Hook utility functions which are outside the component tree.

How to get access to the translation object there?

Paul Razvan Berg
  • 16,949
  • 9
  • 76
  • 114

3 Answers3

6

This seems to work, import i18next rather than react-i18next:

// import { useTranslation } from "react-i18next";
import i18next from "i18next";
function hello() {
    return i18next.t("hello");
}
wessel
  • 534
  • 5
  • 15
5

This one worked for me,

//import i18next

import i18next from 'i18next';

//Then where ever you need to try like this

i18next.t('common:messages.errorMessage')
  • This worked for me, although I needed to change the i18n config by adding the "ns" and "defaultNs" properties. Also, a common mistake is that the JSON file is "broken", meaning that you had a key-value pair where the value contains quotes, make sure you put "\" before each quote. – Filip BRSJAK Jul 26 '23 at 13:39
-3

Not sure if it will work, but can you try this:

import i18n from "react-i18next";

// Then where ever you need try to this

i18n.t("target")
Sagynbek Kenzhebaev
  • 360
  • 1
  • 5
  • 14
  • @PaulRazvanBerg , what about to set i18n.t function to a Static property of Class or something, and then reach that i18n.t function statically from outside component – Sagynbek Kenzhebaev Nov 10 '19 at 16:02