Paul Razvan Berg
Paul Razvan Berg

Reputation: 21390

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

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?

Upvotes: 8

Views: 6970

Answers (4)

Rodder
Rodder

Reputation: 359

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");

Upvotes: 0

Muhammed Shaheer K V
Muhammed Shaheer K V

Reputation: 69

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')

Upvotes: 6

wessel
wessel

Reputation: 564

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");
}

Upvotes: 7

Sagynbek Kenzhebaev
Sagynbek Kenzhebaev

Reputation: 360

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")

Upvotes: -3

Related Questions