mirror of
https://github.com/vercel/commerce.git
synced 2025-07-22 20:26:49 +00:00
Adding Click Outside
This commit is contained in:
45
lib/click-outside/click-outside.tsx
Normal file
45
lib/click-outside/click-outside.tsx
Normal file
@@ -0,0 +1,45 @@
|
||||
import React, { forwardRef, useEffect, Ref, MouseEvent } from 'react'
|
||||
import hasParent from './has-parent'
|
||||
|
||||
interface ClickOutsideProps {
|
||||
active: boolean
|
||||
onClick: (e?: MouseEvent) => void
|
||||
children: any
|
||||
}
|
||||
|
||||
const ClickOutside = (
|
||||
{ active = true, onClick, children }: ClickOutsideProps,
|
||||
ref: Ref<HTMLDivElement> | null | any = {}
|
||||
) => {
|
||||
console.log('--------', active, '-----------')
|
||||
const innerRef = ref?.current
|
||||
|
||||
const handleClick = (event: any) => {
|
||||
console.log(innerRef, event.target)
|
||||
if (!hasParent(event.target, innerRef)) {
|
||||
if (typeof onClick === 'function') {
|
||||
event.preventDefault()
|
||||
event.stopImmediatePropagation()
|
||||
onClick(event)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
useEffect(() => {
|
||||
if (active) {
|
||||
document.addEventListener('mousedown', handleClick)
|
||||
document.addEventListener('touchstart', handleClick)
|
||||
}
|
||||
|
||||
return () => {
|
||||
if (active) {
|
||||
document.removeEventListener('mousedown', handleClick)
|
||||
document.removeEventListener('touchstart', handleClick)
|
||||
}
|
||||
}
|
||||
})
|
||||
|
||||
return React.cloneElement(children, { ref })
|
||||
}
|
||||
|
||||
export default forwardRef(ClickOutside)
|
Reference in New Issue
Block a user