forked from crowetic/commerce
forwardRef
This commit is contained in:
parent
95897aa1c5
commit
3770ad7ea8
@ -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
|
||||||
|
Loading…
x
Reference in New Issue
Block a user