How to use react-i18next in a utility function outside the component tree?
Asked Answered
A

4

7

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?

Arrack answered 9/11, 2019 at 19:32 Comment(0)
K
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");
}
Kalk answered 22/7, 2020 at 13:44 Comment(0)
P
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')
Philippine answered 1/7, 2021 at 8:9 Comment(1)
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.Communicable
H
0

A few steps that worked for me in a similar situation:

  1. in i18n.ts file:

i18n.use(initReactI18next).init({ ns: "en", ......

  1. in non-Hook utility function:

import i18next from "i18next";

import en from "../assets/locales/en.json";

i18next.addResourceBundle("en", "en", en);

const { t } = i18next;

t("some.test.key");

Hamlet answered 21/5 at 15:41 Comment(0)
C
-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")
Ceremony answered 9/11, 2019 at 20:6 Comment(1)
@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 componentCeremony

© 2022 - 2024 — McMap. All rights reserved.