i18n missingKey issue while using i18n instance - reactjs

I am trying to integrate i18next to my project. I have created an instance and made configurations. But when I build my project, I get missingKey error in which they are not inside React component, which means the function t is called with i18n instance.
i18next config:
import i18n from 'i18next';
import LanguageDetector from 'i18next-browser-languagedetector';
import { initReactI18next } from 'react-i18next';
import englishTranslation from './translations/messages-en.json';
import turkishTranslation from './translations/messages-tr.json';
import arabicTranslation from './translations/messages-ar.json';
const detectorOptions = {
// order and from where user language should be detected
order: ['querystring', 'cookie', 'localStorage', 'navigator', 'htmlTag', 'path', 'subdomain'],
// keys or params to lookup language from
lookupQuerystring: 'lang',
lookupCookie: 'i18next',
lookupLocalStorage: 'i18nextLng',
lookupFromPathIndex: 0,
lookupFromSubdomainIndex: 0,
// cache user language on
caches: ['localStorage', 'cookie'],
excludeCacheFor: ['cimode'], // languages to not persist (cookie, localStorage)
// optional expire and domain for set cookie
// cookieMinutes: 10,
// cookieDomain: 'myDomain',
// optional htmlTag with lang attribute, the default is:
htmlTag: document.documentElement,
// only detect languages that are in the whitelist
checkWhitelist: true,
// optional set cookie options, reference:[MDN Set-Cookie docs](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Set-Cookie)
cookieOptions: { path: '/' },
};
const languageDetector = new LanguageDetector();
languageDetector.init(detectorOptions);
i18n
.use(initReactI18next)
.use(languageDetector)
.init({
lng: 'en',
debug: true,
resources: {
en: englishTranslation,
tr: turkishTranslation,
ar: arabicTranslation,
},
interpolation: {
escapeValue: false,
},
fallbackLng: 'en',
whitelist: ['en', 'tr', 'ar'],
});
i18n.on('languageChanged', language => i18n.reloadResources()
.then(() => console.log('Language changed to: ', language)));
export default i18n;
Console error:
i18next::translator: missingKey en translation systemPreparation systemPreparation
index.js:1 i18next::translator: missingKey en translation letsStart letsStart
index.js:1 i18next::translator: missingKey en translation infoAndApproval infoAndApproval
index.js:1 i18next::translator: missingKey en translation nextStep nextStep
...
and it goes like that.
The Javascript file that I am calling i18n instance:
import i18n from '../../../i18n';
export const property = {
text: i18n.t('videoRecording')
};

'videoRecording' keys is missing in messages-en.json file. Checkout also if the messages-en.json file have proper format, which should look as follow:
{
"videoRecording": "some translation"
}
I recommend you to use some tool for handling such situations.
Here is my config example
import i18n from 'i18next'
import Backend from 'i18next-http-backend'
import LanguageDetector from 'i18next-browser-languagedetector'
import { initReactI18next } from 'react-i18next'
const projectToken = "5e13e3019cff4dc6abe36009445f0883";
const loadPath = `https://cdn.simplelocalize.io/${projectToken}/_latest/i18next/{{lng}}/{{ns}}/_index`;
i18n
.use(Backend)
.use(LanguageDetector)
.use (initReactI18next)
.init({
// default/fallback language
fallbackLng: 'en',
ns: ["default"],
defaultNS: "default",
//detects and caches a cookie from the language provided
detection: {
order: ['queryString', 'cookie'],
cache: ['cookie']
},
interpolation: {
escapeValue: false
},
backend: {
loadPath
}
})
export default i18n;
Full project code: https://github.com/simplelocalize/simplelocalize-i18next

Related

is any way to create json file from en.json to all other languages in locals folder for react project translation support to use react i18next

**Is any way to automatically create all languages json file from en.json in locals folder for react project translation support react i18next **
my i18n.js configuration as below
...
import i18n from 'i18next';
import { initReactI18next } from 'react-i18next';
import LanguageDetector from 'i18next-browser-languagedetector';
import Backend from 'i18next-http-backend';
import { DateTime } from 'luxon';
i18n
// i18next-http-backend
// loads translations from your server
// https://github.com/i18next/i18next-http-backend
.use(Backend)
// detect user language
// learn more: https://github.com/i18next/i18next-browser-languageDetector
.use(LanguageDetector)
// pass the i18n instance to react-i18next.
.use(initReactI18next)
// init i18next
// for all options read: https://www.i18next.com/overview/configuration-options
.init({
debug: true,
fallbackLng: 'en',
interpolation: {
escapeValue: false, // not needed for react as it escapes by default
// format: (value, format, lng) => { // legacy usage
// if (value instanceof Date) {
// return DateTime.fromJSDate(value).setLocale(lng).toLocaleString(DateTime[format])
// }
// return value;
// }
}
});
// new usage
i18n.services.formatter.add('DATE_HUGE', (value, lng, options) => {
return DateTime.fromJSDate(value).setLocale(lng).toLocaleString(DateTime.DATE_HUGE)
});
export default i18n;
...
and i am using it as below in my components:-
...{t('footer.date', { date: new Date(), context: getGreetingTime() })}...

i18next missing key but other key was found

I dont understand nothing anymore.
I use i18next and want to access to my key but it does not work.
i18next::translator: missingKey de translation profile profile
i18next::translator: missingKey de translation profile profile
i18next::translator: missingKey de translation profile profile
this is my translation.json
{
"app_name": "Test (NEW DE)",
"profile": "ss"
}
this works:
<Text>{ t('app_name') }</Text>
this not working:
<Text>{ t('profile') }</Text>
can anyone explain me why its not working correctly ?
i18next
import i18next from "i18next";
import { initReactI18next } from "react-i18next";
import LanguageDetector from 'i18next-browser-languagedetector';
import HttpApi from 'i18next-http-backend';
i18next
.use(HttpApi)
.use(LanguageDetector)
.use(initReactI18next)
.init({
react: {
useSuspense: false
},
fallbackLng: 'en',
compatibilityJSON: 'v3',
lng: 'de',
debug: process.env.NODE_ENV === 'development',
backend: {
loadPath: `http://192.168.0.249:4000/public/locales/{{lng}}/translation.json`,
},
interpolation: {
escapeValue: false,
},
keySeparator: '.',
});
export default i18next;
I suspect, you're calling the t function too early and are not waiting for the translations to be fully loaded.
If you're not using suspense: useSuspense: false you need to make sure you check for the ready flag instead.
https://react.i18next.com/latest/usetranslation-hook#not-using-suspense
// additional ready will state if translations are loaded or not
const { t, i18n, ready } = useTranslation('ns1');
https://react.i18next.com/latest/withtranslation-hoc#not-using-suspense
// use tReady prop in MyComponent to check if translations
// are already loaded or not
const ExtendedComponent = withTranslation()(MyComponent);
<ExtendedComponent />

react-i18next addResourceBundle is not a function

I'm using react-i18next to internationalize my react app. When I trying to addResourceBundle on each module's config files it throws this error:
TypeError:
i18next__WEBPACK_IMPORTED_MODULE_0__.default.addResourceBundle is not
a function
Therefore, I added i18next.init command before addResourceBundle. Then it works, but show below warning and reset previously selected locale.
i18next: init: i18next is already initialized. You should call init
just once!
This is my i18n.tsx file
import i18n from 'i18next'
import Backend from 'i18next-http-backend'
import LanguageDetector from 'i18next-browser-languagedetector'
import { initReactI18next } from 'react-i18next'
i18n
.use(Backend)
.use(LanguageDetector)
.use (initReactI18next)
.init({
fallbackLng: 'en',
debug: true,
detection: {
order: ['queryString', 'cookie'],
cache: ['cookie']
},
interpolation: {
escapeValue: false
},
react: {
wait: true,
useSuspense: false,
}
})
export default i18n;
This is my Module's Config file
import i18next from 'i18next';
import { lazy } from 'react';
import en from '../../i18n/dashboard/en';
import si from '../../i18n/dashboard/si';
import ta from '../../i18n/dashboard/ta';
i18next.init({ resources: {} });
i18next.addResourceBundle('en', 'dashboard', en);
i18next.addResourceBundle('si', 'dashboard', si);
i18next.addResourceBundle('ta', 'dashboard', ta);
const DashboardConfig = {
settings: {
layout: {
mode : 'default'
}
},
routes: [
{
path: '/dashboard',
component: lazy(() => import('./Dashboard')),
auth : ['admin', 'user', 'DASHBOARD_VIEW'],
}
]
};
export default DashboardConfig;
it happens, because you are importing i18next in your module instead of created instance in i18n.tsx.
it should be like this:
import i18next from 'path/to/i18n.tsx';

i18n.language is undefined in the url

I have a language detection mechanism from the url lang code. If user is accessing authenticated page without access token, I redirect to login page in the Routes.js.
return user ? (
<Component {...props} />
) : (
<Redirect to={langUrl(`login`)} />
);
LangUrl is a helper function to get url with correct lang code
export const langUrl = (url) => {
return '/'+ i18n.language +'/'+ url;
};
But I get an undefined in the i18n.language, the redirect url is "/undefined/login". My i18n init file is below
import i18n from 'i18next'
import { initReactI18next } from 'react-i18next'
import HttpApi from 'i18next-http-backend'
import LanguageDetector from 'i18next-browser-languagedetector'
i18n
.use(HttpApi)
.use(LanguageDetector)
.use(initReactI18next)
.init({
supportedLngs: ['en', 'ar'],
fallbackLng: 'ar',
debug: false,
// Options for language detector
detection: {
order: ['path', 'cookie', 'htmlTag'],
caches: ['cookie'],
},
react: { useSuspense: false },
defaultNS: 'translation',
backend: {
loadPath: '/assets/locales/{{lng}}/{{ns}}.json',
},
});
export default i18n;
What is the best way to initiliaze the i18n correctly so that language is not undefined?
adding the following value initImmediate: false, in i18n config file
please check the full answer here
i18n.language undefined in react.js

Gatsby - SSR i18n translation are loaded on client

I have a multilingual gatsby website, I try to improve the lighthouse performance score, so i followed this guide to generate my page with the translation in the html. Here is my gatsby-ssr.js file
import { renderToString } from 'react-dom/server'
import Backend from 'i18next-sync-fs-backend'
import i18n from "./src/locales/i18n"
const namespaces = [...my ns...];
export const replaceRenderer = ({ bodyComponent, replaceBodyHTMLString }) => {
i18n
.use(Backend)
.init({
initImmediate: false,
backend: {
loadPath: 'src/locales/{{lng}}/{{ns}}.json',
},
})
// load the common namespace
.loadNamespaces(namespaces, (err) => {
replaceBodyHTMLString(renderToString(bodyComponent))
})
}
My i18n.js file :
import i18n from "i18next";
import Backend from "i18next-xhr-backend";
import LanguageDetector from "i18next-browser-languagedetector";
import { reactI18nextModule } from "react-i18next";
i18n
.use(Backend)
.use(LanguageDetector)
.use(reactI18nextModule)
.init({
fallbackLng: "fr",
ns: ['translation'],
defaultNS: 'translation',
load: 'languageOnly',
debug: false,
interpolation: {
escapeValue: false, // not needed for react!!
},
react: {
wait: true,
},
});
export default i18n;
I use the HOC withNamespaces from react-i18next (v8) in my page like that export default withNamespaces('home')(IndexPage);
This works well because the generated HTML has all the text translated but when I access to my page the client will load a second time the translation and re-render the page, this cause a flickering on the page and big layout shift so lighthouse really not like it. I believe this is in relation with i18next-xhr-backend but I'm stuck.
I expect my page to not load the translation on page load, because the html has already the text translated so I don't need to load translation again

Resources