remember language preference

This commit is contained in:
myl7
2022-02-12 22:26:25 +08:00
parent c6abeeb8aa
commit 37ce14f16c
3 changed files with 41 additions and 2 deletions
+11 -2
View File
@@ -4,6 +4,7 @@ import { Menu, Transition } from '@headlessui/react'
import { useRouter } from 'next/router'
import Link from 'next/link'
import { useCookies, withCookies } from 'react-cookie'
// https://headlessui.dev/react/menu#integrating-with-next-js
const CustomLink = ({ href, children, as, locale, ...props }): JSX.Element => {
@@ -28,6 +29,8 @@ const localeText = (locale: string): string => {
const SwitchLang = () => {
const { locales, pathname, query, asPath } = useRouter()
const [_, setCookie] = useCookies(['NEXT_LOCALE'])
return (
<div className="relative">
<Menu>
@@ -48,7 +51,13 @@ const SwitchLang = () => {
<Menu.Items className="absolute top-0 right-0 z-20 mt-8 w-28 divide-y divide-gray-900 overflow-auto rounded border border-gray-900/10 bg-white py-1 shadow-lg focus:outline-none dark:border-gray-500/30 dark:bg-gray-900 dark:text-white">
{locales!.map(locale => (
<Menu.Item key={locale}>
<CustomLink key={locale} href={{ pathname, query }} as={asPath} locale={locale}>
<CustomLink
key={locale}
href={{ pathname, query }}
as={asPath}
locale={locale}
onClick={() => setCookie('NEXT_LOCALE', locale, { path: '/' })}
>
<div className="m-1 cursor-pointer rounded px-2 py-1 text-left text-sm font-medium hover:bg-blue-50 hover:text-blue-700 dark:hover:bg-blue-600/10 dark:hover:text-blue-400">
{localeText(locale)}
</div>
@@ -62,4 +71,4 @@ const SwitchLang = () => {
)
}
export default SwitchLang
export default withCookies(SwitchLang)