0

I want to add translator for my project but i18next show key and have missing key error in console.

  • my translations path: src/locales/{Language}/translation.json

  • i18n.ts code in src directory:

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

i18n.use(Backend)
  .use(LanguageDetector)
  .use(initReactI18next)
  .init({
    fallbackLng: "en",
    debug: true,
    interpolation: {
      escapeValue: false,
    },
    backend: {
      loadPath: "./locales/{{lng}}/translation.json",
    },
  });

export default i18n;
  • react-i18next.d.ts code :
import "react-i18next";
import en from "./src/locales/en/translation.json";
import fa from "./src/locales/fa/translation.json";

declare module "react-i18next" {
  interface Resources {
    en: typeof en;
    fa: typeof fa;
  }
}

and translation.json is like this:

{
    "Hello": "Hello World"
}
  • use in component:
import { useTranslation } from "react-i18next";

function hello (){

  const { t, i18n } = useTranslation();

  return (
    <div>
      <h1> {t("Hello")}</h1>
    </div>

  );
}

2 Answers 2

0

first change i18.ts file to i18nProvider and add your code into useEffect like this

const I18nProvider: React.FunctionComponent = (props) => {
    useEffect(() => {
       i18n.use(Backend)
      .use(LanguageDetector)
      .use(initReactI18next)
      .init({
        fallbackLng: "en",
        debug: true,
        interpolation: {
          escapeValue: false,
        },
        backend: {
          loadPath: "./locales/{{lng}}/translation.json",
        },
      });
 }, []);
  return (
     <Suspense fallback={<h1>Loading ...</h1>}>
    <I18nextProvider i18n={i18n}>{props.children}</I18nextProvider>
     </Suspense>
  );

second add i18Provider to your _app like this:

const MyApp = ({ Component, pageProps }) => {
  return (
      <I18nProvider>
            <Component {...pageProps} />
      </I18nProvider>
  );
};

export default MyApp;
Sign up to request clarification or add additional context in comments.

Comments

0

The problem is solved, if you have the same problem, just follow the example below. The problem will be solved. Note that even the names of the folders and their location should be the same as the example.

Link: https://dev.to/adrai/how-to-properly-internationalize-a-react-application-using-i18next-3hdb

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.