Reputation: 28
I am using i18next in a Gatsby and React app to handle internationalization. The website is in french and english and works well. The only issue is that when I set the language to french and refresh, I notice a short delay where language is not yet loaded, so it gives me english version (which is the language I set for fallback), and quickly returns to french.
My i18next config file:
import i18n from "i18next";
import fr from "./i18n/fr.json";
import en from "./i18n/en.json";
import { initReactI18next } from "react-i18next";
import LanguageDetector from "i18next-browser-languagedetector";
const resources = {
fr: {
translation: fr
},
en: {
translation: en
}
};
i18n
.use(LanguageDetector)
.use(initReactI18next)
.init({
resources,
fallbackLng: "en",
returnObjects: true,
interpolation: {
escapeValue: false
}
});
export default i18n;
Do you have any idea how to remove this delay and load the page directly to the chosen language ?
Upvotes: 0
Views: 1854
Reputation: 6121
I suppose the fallback language is server-side rendered, and other languages are not.
If you click "view page source" in the browser you can see the original HTML code. I suppose you will see the english text, even if french is displayed on the page.
(Note that "inspect" will display french, because this includes all dynamic changes to the DOM, while "view page source" will display the original server response.)
So you need to render non-default languages on the server as well:
I don't use i18next, but you probably need to set the "initial store" to the desired language on the server-side, instead of set the fallback language as "initial store" and set the desired langage afterwards.
I read that you can set initialI18nStore
and initialLanguage
for the I18nextProvider
See also react.i18next Server Side Rendering
Upvotes: 0
Reputation: 11
I had this problem. Firstly, I changed fallbackLng like this
import Cookies from 'js-cookie';
const cookieLanguage = Cookies.get('i18next');
fallbackLng: cookieLanguage ? cookieLanguage : 'en'
then I wrote in my onClick function
const [langChanged, setLangChanged] = useState(null);
const language = Cookies.get('i18next');
const changeLanguageHandler = (e) => {
const newLang = e.target.innerText.toLowerCase();
if (language !== newLang) {
window.location.reload(true);
broadcastChannel.postMessage("language changed");
setLangChanged(newLang);
}
}
And I used langChanged state like dependency in useEffect
useEffect(() => {
if (langChanged) {
i18next.changeLanguage(langChanged)
}
}, [langChanged])
So it returns same delay to every language
Upvotes: 1