mirror of
https://github.com/vercel/commerce.git
synced 2025-03-14 22:42:33 +00:00
forwardRef
This commit is contained in:
parent
95897aa1c5
commit
3770ad7ea8
@ -7,37 +7,39 @@ interface ClickOutsideProps {
|
||||
children: any
|
||||
}
|
||||
|
||||
const ClickOutside = (
|
||||
{ active = true, onClick, children }: ClickOutsideProps,
|
||||
ref: Ref<HTMLDivElement> | null | any = {}
|
||||
) => {
|
||||
const innerRef = ref?.current
|
||||
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)
|
||||
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 () => {
|
||||
useEffect(() => {
|
||||
if (active) {
|
||||
document.removeEventListener('mousedown', handleClick)
|
||||
document.removeEventListener('touchstart', handleClick)
|
||||
document.addEventListener('mousedown', 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