4
0
forked from crowetic/commerce

forwardRef

This commit is contained in:
Belen Curcio 2020-12-02 13:24:25 -03:00
parent 95897aa1c5
commit 3770ad7ea8

View File

@ -7,37 +7,39 @@ interface ClickOutsideProps {
children: any children: any
} }
const ClickOutside = ( const ClickOutside = forwardRef(
{ active = true, onClick, children }: ClickOutsideProps, (
ref: Ref<HTMLDivElement> | null | any = {} { active = true, onClick, children }: ClickOutsideProps,
) => { ref: Ref<HTMLDivElement> | null | any = {}
const innerRef = ref?.current ) => {
const innerRef = ref?.current
const handleClick = (event: any) => { const handleClick = (event: any) => {
if (!hasParent(event.target, innerRef)) { if (!hasParent(event.target, innerRef)) {
if (typeof onClick === 'function') { if (typeof onClick === 'function') {
event.preventDefault() event.preventDefault()
event.stopImmediatePropagation() event.stopImmediatePropagation()
onClick(event) onClick(event)
}
} }
} }
}
useEffect(() => { useEffect(() => {
if (active) {
document.addEventListener('mousedown', handleClick)
document.addEventListener('touchstart', handleClick)
}
return () => {
if (active) { if (active) {
document.removeEventListener('mousedown', handleClick) document.addEventListener('mousedown', handleClick)
document.removeEventListener('touchstart', handleClick) document.addEventListener('touchstart', handleClick)
} }
}
})
return React.cloneElement(children, { ref }) return () => {
} if (active) {
document.removeEventListener('mousedown', handleClick)
document.removeEventListener('touchstart', handleClick)
}
}
})
export default forwardRef(ClickOutside) return React.cloneElement(children, { ref })
}
)
export default ClickOutside