Reputation: 474
I am trying i18n in react. I have files structure like below
src/i18n/i18n.js => Part of this file is below
import Backend from "i18next-http-backend";
await i18n
.use(Backend) // We use this to load the translation files dynamically
.use(initReactI18next) // React bindings
.init({
debug: true,
resources: {},
fallbackLng: "en", // Default fallback language
missingKeyHandler: (lng, ns, key, fallbackValue) => {
console.log(`Missing key: ${key} in ${lng}`);
return fallbackValue || `Missing translation for ${key}`;
},
lng: language, // Set the initial language
interpolation: {
escapeValue: false, // No escaping needed
},
ns: ["translation"], // Default namespace is 'translation'
defaultNS: "translation", // Specify default namespace
backend: {
loadPath: "/locales/{{lng}}/translation.json", // Path to load language files
allowMultiLoading: false,
request: function (options) {
// Disable caching for testing
options.headers["Cache-Control"] = "no-cache";
return fetch(options.url, options);
},
},
react: {
useSuspense: false, // Disable React Suspense for dynamic loading
},
// resources: {
// en: {
// translation: {
// welcome_message: "Welcome to our app!",
// },
// },
// es: {
// translation: {
// welcome_message: "¡Bienvenido a nuestra aplicación!",
// },
// },
// },
load: "languageOnly", // Load only the language files (e.g., translation.json)
})
.then(() => {
console.log("i18next initialized successfully");
})
.catch((error) => {
console.error("Error initializing i18next:", error);
});
public/locales/en/translation.json
public/locales/fr/translation.json
{
"header": {
"welcome_message": "Welcome to our app!"
}
}
Issue that I am facing is when I access {t("header.welcome_message")}
in my component then its not getting translated or showing that message. Just showing like header.welcome_message
I checked by accessing url http://localhost:3000/locales/en/translation.json
, it shows data of that file.
also checked statically in resources
which is working.
It's not working dynamically with files.
My console shows like below
What is missing or getting wrong ? Please help and guide.
Upvotes: 0
Views: 38