'React Typescript i18next missing key error
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>
);
}
Solution 1:[1]
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
Solution 2:[2]
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;
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | EhsaN |
| Solution 2 | milad emami |
