Adding Click Outside

This commit is contained in:
Belen Curcio
2020-12-02 13:16:30 -03:00
parent c37ed3d418
commit 6020d5cfd2
5 changed files with 107 additions and 45 deletions

View File

@@ -1,9 +1,10 @@
import cn from 'classnames'
import Link from 'next/link'
import { FC, useState } from 'react'
import { useRef, FC, useState } from 'react'
import { useRouter } from 'next/router'
import s from './I18nWidget.module.css'
import { Cross, ChevronUp } from '@components/icons'
import ClickOutside from '@lib/click-outside'
interface LOCALE_DATA {
name: string
img: {
@@ -37,55 +38,62 @@ const I18nWidget: FC = () => {
defaultLocale = 'en-US',
asPath: currentPath,
} = useRouter()
const options = locales?.filter((val) => val !== locale)
const currentLocale = locale || defaultLocale
const ref = useRef<HTMLDivElement | null>(null)
return (
<nav className={s.root}>
<div className="flex items-center relative">
<button className={s.button} aria-label="Language selector">
<img
className="block mr-2 w-5"
src={`/${LOCALES_MAP[currentLocale].img.filename}`}
alt={LOCALES_MAP[currentLocale].img.alt}
/>
{options && (
<span
className="cursor-pointer"
onClick={() => setDisplay(!display)}
>
<ChevronUp className={cn({ [s.icon]: display })} />
</span>
)}
</button>
</div>
<div className="absolute top-0 right-0">
{options?.length && display ? (
<div className={s.dropdownMenu}>
<div className="flex flex-row justify-end px-6">
<button
onClick={() => setDisplay(false)}
aria-label="Close panel"
className={s.closeButton}
>
<Cross className="h-6 w-6" />
</button>
<ClickOutside active={display} onClick={() => setDisplay(false)} ref={ref}>
<nav className={s.root}>
<div
className="flex items-center relative"
onClick={() => setDisplay(!display)}
>
<button className={s.button} aria-label="Language selector">
<img
className="block mr-2 w-5"
src={`/${LOCALES_MAP[currentLocale].img.filename}`}
alt={LOCALES_MAP[currentLocale].img.alt}
/>
{options && (
<span className="cursor-pointer">
<ChevronUp className={cn({ [s.icon]: display })} />
</span>
)}
</button>
</div>
<div className="absolute top-0 right-0">
{options?.length && display ? (
<div className={s.dropdownMenu}>
<div className="flex flex-row justify-end px-6">
<button
onClick={() => setDisplay(false)}
aria-label="Close panel"
className={s.closeButton}
>
<Cross className="h-6 w-6" />
</button>
</div>
<ul>
{options.map((locale) => (
<li key={locale}>
<Link href={currentPath} locale={locale}>
<a
className={cn(s.item)}
onClick={() => setDisplay(false)}
>
{LOCALES_MAP[locale].name}
</a>
</Link>
</li>
))}
</ul>
</div>
<ul>
{options.map((locale) => (
<li key={locale}>
<Link href={currentPath} locale={locale}>
<a className={cn(s.item)} onClick={() => setDisplay(false)}>
{LOCALES_MAP[locale].name}
</a>
</Link>
</li>
))}
</ul>
</div>
) : null}
</div>
</nav>
) : null}
</div>
</nav>
</ClickOutside>
)
}