Search code examples
reactjsinternationalizationi18nextreact-i18nextreact-error-boundary

How to fix useTranslation error in react-i18next


My error boundary caught error with useTranslation hook from i18next. I can't get proper error text because of that error boundary. Just got text like "above error occured in ...". Can you give me any ideas why is this happening?

Problems with this line:

const {t} = useTranslation();

i18 config:

import i18next from "i18next";
import {initReactI18next} from "react-i18next";
import HttpApi from "i18next-http-backend";
import LanguageDetector from "i18next-browser-languagedetector";

export const ns = ["translation", "notification", "form", "modal", "table", "plans"];

i18next
  .use(initReactI18next)
  .use(HttpApi)
  .use(LanguageDetector)
  .init({
    supportedLngs: ["en", "ru"],
    fallbackLng: "en",
    nonExplicitSupportedLngs: false,
    cleanCode: true,
    ns: ns,
    debug: process.env.NODE_ENV === "development",
    interpolation: {
      format: function (value, format) {
        if (format === "uppercase") return value.toUpperCase();
        if (format === "lowercase") return value.toLowerCase();
      }
    }
  });

export default i18next;

I used useTranslation in error boundary, however, removing it is not a solution.


Solution

  • You can't use a react hook inside a class component.

    However, you can create a HOC to forward translations to the Error Boundary component.

    Follow this link for more details of how to do that.