mirror of
https://github.com/vercel/commerce.git
synced 2025-04-24 20:07:50 +00:00
Disable & Block Scroll and Click Outside for Dropdown Menu
This commit is contained in:
parent
3f5045d3a8
commit
95897aa1c5
@ -1,12 +1,18 @@
|
||||
import cn from 'classnames'
|
||||
import Link from 'next/link'
|
||||
import { FC, useState } from 'react'
|
||||
import { FC, useRef, useState, useEffect } from 'react'
|
||||
import { useTheme } from 'next-themes'
|
||||
import { useRouter } from 'next/router'
|
||||
import s from './DropdownMenu.module.css'
|
||||
import { Avatar } from '@components/common'
|
||||
import { Moon, Sun } from '@components/icons'
|
||||
import { useUI } from '@components/ui/context'
|
||||
import ClickOutside from '@lib/click-outside'
|
||||
import {
|
||||
disableBodyScroll,
|
||||
enableBodyScroll,
|
||||
clearAllBodyScrollLocks,
|
||||
} from 'body-scroll-lock'
|
||||
|
||||
import useLogout from '@bigcommerce/storefront-data-hooks/use-logout'
|
||||
interface DropdownMenuProps {
|
||||
@ -34,8 +40,23 @@ const DropdownMenu: FC<DropdownMenuProps> = ({ open = false }) => {
|
||||
const { theme, setTheme } = useTheme()
|
||||
const [display, setDisplay] = useState(false)
|
||||
const { closeSidebarIfPresent } = useUI()
|
||||
const ref = useRef() as React.MutableRefObject<HTMLUListElement>
|
||||
|
||||
useEffect(() => {
|
||||
if (ref.current) {
|
||||
if (display) {
|
||||
disableBodyScroll(ref.current)
|
||||
} else {
|
||||
enableBodyScroll(ref.current)
|
||||
}
|
||||
}
|
||||
return () => {
|
||||
clearAllBodyScrollLocks()
|
||||
}
|
||||
}, [display])
|
||||
|
||||
return (
|
||||
<ClickOutside active={display} onClick={() => setDisplay(false)}>
|
||||
<div>
|
||||
<button
|
||||
className={s.avatarButton}
|
||||
@ -44,9 +65,8 @@ const DropdownMenu: FC<DropdownMenuProps> = ({ open = false }) => {
|
||||
>
|
||||
<Avatar />
|
||||
</button>
|
||||
|
||||
{display && (
|
||||
<ul className={s.dropdownMenu}>
|
||||
<ul className={s.dropdownMenu} ref={ref}>
|
||||
{LINKS.map(({ name, href }) => (
|
||||
<li key={href}>
|
||||
<div>
|
||||
@ -93,6 +113,7 @@ const DropdownMenu: FC<DropdownMenuProps> = ({ open = false }) => {
|
||||
</ul>
|
||||
)}
|
||||
</div>
|
||||
</ClickOutside>
|
||||
)
|
||||
}
|
||||
|
||||
|
Loading…
x
Reference in New Issue
Block a user