forked from LAION-AI/Open-Assistant
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathLanguageSelector.tsx
55 lines (49 loc) · 1.72 KB
/
LanguageSelector.tsx
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
import { Select } from "@chakra-ui/react";
import { useRouter } from "next/router";
import { useTranslation } from "next-i18next";
import { useCallback, useEffect, useMemo } from "react";
import { useCookies } from "react-cookie";
import { getLocaleDisplayName } from "src/lib/languages";
const LanguageSelector = () => {
const router = useRouter();
const [cookies, setCookie] = useCookies(["NEXT_LOCALE"]);
const { i18n } = useTranslation();
// Inspect the cookie based locale and the router based locale. If the user
// has manually set the locale via URL, they will differ. In that condition,
// update the cookie.
useEffect(() => {
const localeCookie = cookies["NEXT_LOCALE"];
const localeRouter = router.locale;
if (localeRouter !== localeCookie) {
setCookie("NEXT_LOCALE", localeRouter, { path: "/" });
}
}, [cookies, setCookie, router]);
// Memo the set of locales and their display names.
const localesAndNames = useMemo(() => {
return router.locales!.map((locale) => ({
locale,
name: getLocaleDisplayName(locale),
}));
}, [router.locales]);
const languageChanged = useCallback(
async (option) => {
const locale = option.target.value;
setCookie("NEXT_LOCALE", locale, { path: "/" });
const path = router.asPath;
await router.push(path, path, { locale });
router.reload();
},
[router, setCookie]
);
const { language: currentLanguage } = i18n;
return (
<Select onChange={languageChanged} defaultValue={currentLanguage} maxW="fit-content">
{localesAndNames.map(({ locale, name }) => (
<option key={locale} value={locale}>
{name}
</option>
))}
</Select>
);
};
export { LanguageSelector };