i18n.js
import i18n from 'i18next';
import { initReactI18next } from 'react-i18next';
import enTranslation from '../locales/en.json';
import trTranslation from '../locales/tr.json';
import deTranslation from '../locales/de.json';
import I18nextBrowserLanguageDetector from 'i18next-browser-languagedetector';
const resources = {
en: {
translation:
enTranslation
},
tr: {
translation:
trTranslation
},
de: {
translation:
deTranslation
},
};
i18n.use(initReactI18next).init({
resources,
debug: true,
fallbackLng: 'de',
interpolation: {
escapeValue: false,
},
}).catch(e => console.log(e))
export default i18n;
_app.tsx
export default function App({ Component, pageProps }: AppProps) {
return <>
<Provider store={store}>
<I18nextProvider i18n={i18n}>
<Header />
<Component {...pageProps} />
<Footer />
</I18nextProvider>
<Script src="https://cdn.jsdelivr.net/npm/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="bedcd1d1cacdcaccdfcefe8b908f908d">[email protected]</a>/dist/js/bootstrap.bundle.min.js"></Script>
</Provider>
</>
}
LanguageSelect.tsx -Component in my header
import React, { useEffect } from 'react';
import { useTranslation } from 'react-i18next';
const LanguageSelection = () => {
const { i18n } = useTranslation();
const handleLanguageChange = (event: any) => {
const selectedLanguage = event.target.value;
i18n.changeLanguage(selectedLanguage);
};
return (
<div style={{ zIndex: 99 }}>
<select className='text-sm' defaultValue={i18n.language} id="language" onChange={handleLanguageChange}>
<option value="en">EN</option>
<option value="tr">TR</option>
<option value="de">DE</option>
</select>
</div>
);
};
export default LanguageSelection;
After starting the project, it defaults to DE language. When I switch it to TR or EN, it works fine until I refresh the page. Upon refreshing, it reverts back to DE. I am trying to maintain the last language selection but haven't been successful.
I have attempted various solutions found online, without success:
- Tried removing fallbackLng - received hydrogen errors.
- Tried fallbackLng: localStorage.getItem('i18nextLng') || 'de' - resulted in a "localStorage is not defined" error.
- Tried lng:'de'.
- Tried setting the language detector but couldn't get it to work either.
My goal is to retain the user's last language selection, perhaps based on their browser language preference (which would be ideal).