mirror of
https://github.com/vercel/commerce.git
synced 2025-07-22 20:26:49 +00:00
Adding Click Outside
This commit is contained in:
45
lib/click-outside/click-outside.tsx
Normal file
45
lib/click-outside/click-outside.tsx
Normal 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 = (
|
||||
{ active = true, onClick, children }: ClickOutsideProps,
|
||||
ref: Ref<HTMLDivElement> | null | any = {}
|
||||
) => {
|
||||
console.log('--------', active, '-----------')
|
||||
const innerRef = ref?.current
|
||||
|
||||
const handleClick = (event: any) => {
|
||||
console.log(innerRef, event.target)
|
||||
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 forwardRef(ClickOutside)
|
5
lib/click-outside/has-parent.js
Normal file
5
lib/click-outside/has-parent.js
Normal file
@@ -0,0 +1,5 @@
|
||||
import isInDOM from './is-in-dom'
|
||||
|
||||
export default function hasParent(element, root) {
|
||||
return root && root.contains(element) && isInDOM(element)
|
||||
}
|
1
lib/click-outside/index.ts
Normal file
1
lib/click-outside/index.ts
Normal file
@@ -0,0 +1 @@
|
||||
export { default } from './click-outside'
|
3
lib/click-outside/is-in-dom.js
Normal file
3
lib/click-outside/is-in-dom.js
Normal file
@@ -0,0 +1,3 @@
|
||||
export default function isInDom(obj) {
|
||||
return Boolean(obj.closest('body'))
|
||||
}
|
Reference in New Issue
Block a user