My idea of switching between languages is to click on flag (when clicked, the flag will change as well as the language). I am doing well so far, flag is switching and url path too, but I can not make the switch between translations.
For handling url's I am using build in Next option i18n and for actual language translations I am using react-i18next.
My i18next file is pretty straight forward:
i18n.use(LanguageDetector)
.use(initReactI18next)
.init({
resources: {
en: {
translation: translations_EN_homePage,
},
da: {
translation: translations_DA_homePage,
},},});
Changing language hook and handleOnclick function:
const [language, setLanguage] = useState('en');
const handleOnclick = (e) => {
e.preventDefault();
setLanguage(e.target.value);
i18n.changeLanguage(e.target.value);
};
And finally solution for my button = flag
<button
value={language === 'en' ? 'da' : 'en'}
onClick={() => {
const locale = router.locale === 'en' ? 'da' : 'en';
setCookie(locale);
{handleOnclick}
router.push(
`/${locale}`,
`/${locale}`,
{locale: false,}}} >
{router.locale === 'en' ? (
<img
src={menuItems.data.body[5].items[0].image.url}/>
) : (
<img src={menuItems.data.body[4].items[0].image.url} />
)}
</button>
Why the handleOnclick function is not working ? when I am using just 2 buttons for testing it is working totally fine with translating, so where is it conflicting ?
Example of working handleOnclick funtion, which I dont want to use:
<button value="da" onClick={handleOnclick}>
Danish
</button>
<button value="en" onClick={handleOnclick}>
English
</button>