Reputation: 55
This is my config file:
i18n.js:
import i18n from 'i18next';
import Backend from 'i18next-xhr-backend';
import detector from "i18next-browser-languagedetector";
import { initReactI18next } from 'react-i18next';
const fallbc = ['en'];
const langArr = ['en', 'de'];
i18n
.use(detector)
.use(Backend)
.use(initReactI18next)
.init({
backend: {
loadPath: '/register/locales/{{lng}}/{{ns}}.json'
},
fallck,
debug: true,
whitelist: langArr,
interpolation: {
escapeValue: false,
},
react: {
wait: true,
},
});
export default i18n;
And when I try this:
import i18n from '../i18n';
return (
<div>
<button onClick={() => i18n.changeLanguage('de')}>de</button>
<button onClick={() => i18n.changeLanguage('en')}>en</button>
</div>
);
Only English is rendered, the German is not. What am I doing wrong?
Is something wrong with my configuration? I feel that I am really close to resolving this.
Upvotes: 5
Views: 20822
Reputation: 8135
i18n.Init
is a lazy load function You have to wait for callback
has to be called. Else use SyncBackend. Else start app lazy.
Sample:
import i18next from 'i18next';
import SyncBackend from 'i18next-sync-fs-backend';
// working
i18next
.use(SyncBackend)
.init({ initImmediate: false });
i18next.t('key'); // -> will return value
Lazy Start:
export default (callback) => {
const instance = i18n
.use(detector)
.use(Backend)
.use(initReactI18next)
.init({
backend: {
loadPath: '/register/locales/{{lng}}/{{ns}}.json'
},
fallck,
debug: true,
whitelist: langArr,
interpolation: {
escapeValue: false,
},
react: {
wait: true,
},
},() => callback(instance));
};
import i18nInit from '../i18n';
i18nInit((i18n) =>{
// lazy start here
return (
<div>
<button onClick={() => i18n.changeLanguage('de')}>de</button>
<button onClick={() => i18n.changeLanguage('en')}>en</button>
</div>
);
})
More: https://www.i18next.com/overview/configuration-options
Upvotes: 3