i18next missing key but other key was found - reactjs

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 />

Related

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

React-i18next does not load translations on page reload

I am using react-I18next in my nextjs application. I don't want to use next-I18next because I tried to use it but couldn't make it work. But react-i18next is working in my application for now and I am able to change language from english to german and back. However if I reload the page I get this error.
TypeError: i18n.changeLanguage is not a function
What could be the possibel cause of this error and how can I fix it?
P.S In my app.ts file I am not using Suspense because it gives me this error
ReactDOMServer does not yet support Suspense.
Here is my i18.ts file
/* eslint-disable no-duplicate-imports */
import i18n from 'i18next';
import LanguageDetector from 'i18next-browser-languagedetector';
import backend from 'i18next-xhr-backend';
import { initReactI18next } from 'react-i18next';
import loginDE from '../../public/locales/de/loginDE.json';
import loginEN from '../../public/locales/en/loginEN.json';
// the translations
// (tip move them in a JSON file and import them)
const resources = {
en: {
translation: loginEN,
},
de: {
translation: loginDE,
},
};
void i18n
.use(backend)
.use(LanguageDetector)
.use(initReactI18next) // passes i18n down to react-i18next
.init({
fallbackLng: 'en',
interpolation: {
escapeValue: false, // react already safes from xss
},
resources,
lng: 'en',
keySeparator: false, // we do not use keys in form messages.welcome
react: {
useSuspense: true,
},
});
export default i18n;
ReactDOMServer does not yet support Suspense.
Change your useSuspense value like that:
react: { useSuspense: false },
TypeError: i18n.changeLanguage is not a function
Make sure you wrapped a component with I18nextProvider

Set i18next language based on HTML tag

OK, so I'm experimenting with ReactJS and i18next.
I want to set my translation language on the initial page load based on
some html tag.
For example if I have <html lang="de"> when the page is loaded I would like to have
the lng set to de before any translations take place.
Here's the content of my i18n.js file:
import i18n from "i18next";
import { initReactI18next } from "react-i18next";
// the translations
// (tip move them in a JSON file and import them)
const resources = {
en: {
translation: {
"Welcome to React": "Translation in English"
}
},
de: {
translation: {
"Welcome to React": "Translation in German"
}
}
};
i18n
.use(initReactI18next) // passes i18n down to react-i18next
.init({
resources,
lng: "en",
keySeparator: false, // we do not use keys in form messages.welcome
interpolation: {
escapeValue: false // react already safes from xss
}
});
export default i18n;
From here
const htmlLang = document.documentElement.lang; // for <html lang=".."> not xml-lang:".."
Now you can put this constant in youe i18n declaration
i18n
.use(initReactI18next) // passes i18n down to react-i18next
.init({
resources,
lng: htmlLang,
keySeparator: false, // we do not use keys in form messages.welcome
interpolation: {
escapeValue: false // react already safes from xss
},
fallbackLng: ['en', //'fr', ...]
});
I also add a fallback language

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

i18n missingKey issue while using i18n instance

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

Resources