|
| 1 | +"use client"; |
| 2 | + |
| 3 | +import { usePathname, useRouter } from "next/navigation"; |
| 4 | +import MenuItem from "@mui/material/MenuItem"; |
| 5 | +import Select, { SelectChangeEvent } from "@mui/material/Select"; |
| 6 | + |
| 7 | +const languages = [ |
| 8 | + { code: "en", label: "English" }, |
| 9 | + { code: "uk", label: "Українська" }, |
| 10 | +]; |
| 11 | + |
| 12 | +export default function LanguageSwitcher() { |
| 13 | + const pathname = usePathname(); |
| 14 | + const router = useRouter(); |
| 15 | + |
| 16 | + const currentLang = pathname.split("/")[1] || "en"; |
| 17 | + |
| 18 | + const handleChange = (event: SelectChangeEvent) => { |
| 19 | + const newLang = event.target.value; |
| 20 | + |
| 21 | + // Якщо шлях взагалі порожній app-bar.tsx(наприклад, просто /), то додаємо мову |
| 22 | + if (!pathname) { |
| 23 | + router.push(`/${newLang}`); |
| 24 | + return; |
| 25 | + } |
| 26 | + |
| 27 | + const pathSegments = pathname.split("/"); |
| 28 | + pathSegments[1] = newLang; |
| 29 | + const newPath = pathSegments.join("/"); |
| 30 | + |
| 31 | + router.push(newPath); |
| 32 | + }; |
| 33 | + |
| 34 | + return ( |
| 35 | + <Select |
| 36 | + value={currentLang} |
| 37 | + onChange={handleChange} |
| 38 | + size="small" |
| 39 | + variant="outlined" |
| 40 | + sx={{ |
| 41 | + minWidth: 120, |
| 42 | + color: "inherit", |
| 43 | + ".MuiOutlinedInput-notchedOutline": { |
| 44 | + borderColor: "rgba(255, 255, 255, 0.5)", |
| 45 | + }, |
| 46 | + "&:hover .MuiOutlinedInput-notchedOutline": { |
| 47 | + borderColor: "white", |
| 48 | + }, |
| 49 | + ".MuiSvgIcon-root ": { |
| 50 | + fill: "currentColor", |
| 51 | + }, |
| 52 | + }} |
| 53 | + > |
| 54 | + {languages.map((lang) => ( |
| 55 | + <MenuItem key={lang.code} value={lang.code}> |
| 56 | + {lang.label} |
| 57 | + </MenuItem> |
| 58 | + ))} |
| 59 | + </Select> |
| 60 | + ); |
| 61 | +} |
0 commit comments