better langSwitcher
This commit is contained in:
@ -1,4 +1,9 @@
|
||||
import { useState } from 'react';
|
||||
import { useRouter } from 'next/router';
|
||||
import Menu from '@mui/material/Menu';
|
||||
import MenuItem from '@mui/material/MenuItem';
|
||||
import IconButton from '@mui/material/IconButton';
|
||||
import TranslateIcon from '@mui/icons-material/Translate';
|
||||
import { useTranslations } from 'next-intl';
|
||||
|
||||
// using https://next-intl-docs.vercel.app/docs/getting-started/pages-router
|
||||
@ -7,18 +12,44 @@ const LanguageSwitcher = () => {
|
||||
const router = useRouter();
|
||||
const { locale, locales, asPath } = router;
|
||||
|
||||
const [anchorEl, setAnchorEl] = useState(null);
|
||||
|
||||
const handleClick = (event) => {
|
||||
setAnchorEl(event.currentTarget);
|
||||
};
|
||||
|
||||
const handleClose = () => {
|
||||
setAnchorEl(null);
|
||||
};
|
||||
|
||||
const changeLanguage = (lng) => {
|
||||
router.push(asPath, asPath, { locale: lng });
|
||||
handleClose();
|
||||
};
|
||||
|
||||
return (
|
||||
<div>
|
||||
{locales.map((lng) => {
|
||||
if (lng === locale) return null;
|
||||
return (
|
||||
<button key={lng} onClick={() => router.push(asPath, asPath, { locale: lng })}>
|
||||
{t('changeTo')} {t(lng.toUpperCase())}
|
||||
</button>
|
||||
);
|
||||
})}
|
||||
<IconButton onClick={handleClick} color="inherit">
|
||||
<TranslateIcon />
|
||||
</IconButton>
|
||||
<Menu
|
||||
id="language-menu"
|
||||
anchorEl={anchorEl}
|
||||
keepMounted
|
||||
open={Boolean(anchorEl)}
|
||||
onClose={handleClose}
|
||||
>
|
||||
{locales.map((lng) => {
|
||||
if (lng === locale) return null;
|
||||
return (
|
||||
<MenuItem key={lng} onClick={() => changeLanguage(lng)}>
|
||||
{t('changeTo')} {t(lng.toUpperCase())}
|
||||
</MenuItem>
|
||||
);
|
||||
})}
|
||||
</Menu>
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
export default LanguageSwitcher;
|
||||
export default LanguageSwitcher;
|
||||
|
Reference in New Issue
Block a user