Fix: Prevent click-ouside to lose children ref

This commit is contained in:
lita 2021-12-30 18:21:49 +01:00
parent c95f292743
commit 1ccf5b3870

View File

@ -1,4 +1,5 @@
import React, { useRef, useEffect, MouseEvent } from 'react' import React, { useRef, useEffect, MouseEvent, ReactElement } from 'react'
import mergeRefs from 'react-merge-refs'
import hasParent from './has-parent' import hasParent from './has-parent'
interface ClickOutsideProps { interface ClickOutsideProps {
@ -13,13 +14,9 @@ const ClickOutside = ({
children, children,
}: ClickOutsideProps) => { }: ClickOutsideProps) => {
const innerRef = useRef() const innerRef = useRef()
const child = children ? React.Children.only(children) : undefined
const handleClick = (event: any) => { if (!child) {
if (!hasParent(event.target, innerRef?.current)) { throw new Error('A valid non Fragment React Children should be provided')
if (typeof onClick === 'function') {
onClick(event)
}
}
} }
useEffect(() => { useEffect(() => {
@ -36,7 +33,27 @@ const ClickOutside = ({
} }
}) })
return React.cloneElement(children, { ref: innerRef }) const handleClick = (event: any) => {
if (!hasParent(event.target, innerRef?.current)) {
if (typeof onClick === 'function') {
onClick(event)
}
}
}
const composedRefCallback = (element: ReactElement) => {
if (child) {
if (typeof child.ref === 'function') {
child.ref(element)
} else if (child.ref) {
child.ref.current = element
}
}
}
return React.cloneElement(child, {
ref: mergeRefs([composedRefCallback, innerRef]),
})
} }
export default ClickOutside export default ClickOutside