forked from crowetic/commerce
46 lines
1.1 KiB
TypeScript
46 lines
1.1 KiB
TypeScript
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)
|