I18next: Cannot read property 'translator' of undefined when using t()

Created on 18 Jul 2019  路  3Comments  路  Source: i18next/i18next

Hello,

Having a bit of an issue with my translations for a typescript/react project that my team is working on. We are using the t function to translate components, but are having issues with importing it properly and are consistently getting errors when compiling.

At the top of our files we are importing via

import i18next from "i18next";

then deconstructing the t within the render method of the component like so:

const { t } = i18next

From there, we are calling a specific translation like so:

{t('common:hello'}

Any clue why we would be getting

Uncaught TypeError: Cannot read property 'translator' of undefined

When the application compiles?

When I look into it I see this bit of code that is seemingly causing the issue:

I18n.prototype.t = function t() {
    var _translator;

    return this.translator && (_translator = this.translator).translate.apply(_translator, arguments);
  };

But do not know how to fix it. Thank you!

Most helpful comment

This worked well for me:

const t = i18next.t.bind(i18next)

All 3 comments

you can't deconstruct a function like this...t is not an export on a module...it's a function inside a class expecting being called from the instance like i18next.t you would have to bind that function...

This worked well for me:

const t = i18next.t.bind(i18next)

Building on top of @minodisk's answer, I have added this in the same module where I am initializing i18next (I am using react-i18next, initializing in a top-level i18n.ts):

...
export default i18n;

const t = i18n.t.bind(i18n);
export { t };

so that from other modules, it can be imported as expected:

import { t } from "./i18n";
Was this page helpful?
0 / 5 - 0 ratings