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/[email protected]/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;
When I start the project it comes with DE language, then I switch it to TR or EN it works fine untill I refresh page, after refresh it goes back to DE. I want to keep it on last selection, couldn't achieve it.
I tried many ways that I found on the internet but nothing changed.
Tried remove fallbackLng -> gives hydrogen errors
Tried fallbackLng: localStorage.getItem('i18nextLng') || 'de' -> this gives me localStorage is not defined error
Tried lng:'de'
Tried to set languageDetector but couldn't make it work either...
I want to keep last selection of language, maybe from user's browser language (this would be perfect)
You should do it by hand.
For instance: