Merge branch 'master' into fix

This commit is contained in:
B
2020-12-08 10:46:04 -03:00
committed by GitHub
9 changed files with 221 additions and 111 deletions

View 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 = forwardRef(
(
{ active = true, onClick, children }: ClickOutsideProps,
ref: Ref<HTMLDivElement> | null | any = {}
) => {
const innerRef = ref?.current
const handleClick = (event: any) => {
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 ClickOutside

View File

@@ -0,0 +1,5 @@
import isInDOM from './is-in-dom'
export default function hasParent(element, root) {
return root && root.contains(element) && isInDOM(element)
}

View File

@@ -0,0 +1 @@
export { default } from './click-outside'

View File

@@ -0,0 +1,3 @@
export default function isInDom(obj) {
return Boolean(obj.closest('body'))
}