I have a working solution with i18Next where translation are loaded from the app. Here how it looks
import { initReactI18next } from 'react-i18next';
import EN from './data/locales/en/translation.json';
import DA from './data/locales/da/translation.json';
const resources = {
en: {
translation: EN,
},
da: {
translation: DA,
}
};
i18n
.use(initReactI18next)
.init({
resources,
fallbackLng: 'en',
lng: 'en', // TODO: make dynamic
keySeparator: false,
interpolation: {
escapeValue: false,
},
parseMissingKeyHandler: () => "" // empty string for missing keys
});
export default i18n;
Now we have an external REST API to fetch the translation from. I18Next has a plugin for that 18next-http-backend
. Here is my latest code calling the external service
import {initReactI18next} from 'react-i18next';
import HttpApi from 'i18next-http-backend';
i18n
.use(HttpApi)
.use(initReactI18next)
.init({
backend: {
loadPath: `http://rest-api.com/getfile?name=samplefile&lang=en`,
parse: function (data) {
console.log(data)
},
},
fallbackLng: 'en',
lng: 'en', // TODO: make dynamic
debug: true,
keySeparator: false,
interpolation: {
escapeValue: false,
},
parseMissingKeyHandler: () => "" // empty string for missing keys
});
export default i18n;
And then I am wrapping my app with React Suspense to wait for the translations to be fetched. i18Next is calling the API and fetching the JSON but the translations are not properly loading to the app and I am seeing the translation keys instead of actual content.
i18next::translator: missingKey en translation labels.goToSummary labels.goToSummary
Not sure what I am missing here.
The response from endpoint is like this
{
"labels_actions": "Actions",
"labels_add": "Add",
"labels_goToSummary": "Amount"
}
and on FE I am using it like this
<Link>{t('labels_goToSummary')}</Link>
Seems the problem was only the missing return statement in the parse function:
import {initReactI18next} from 'react-i18next';
import HttpApi from 'i18next-http-backend';
i18n
.use(HttpApi)
.use(initReactI18next)
.init({
backend: {
loadPath: `http://rest-api.com/getfile?name=samplefile&lang=en`,
parse: function (data) {
console.log(data)
return data;
},
},
fallbackLng: 'en',
lng: 'en', // TODO: make dynamic
debug: true,
keySeparator: false,
interpolation: {
escapeValue: false,
},
parseMissingKeyHandler: () => "" // empty string for missing keys
});
export default i18n;