mirror of
https://github.com/vercel/commerce.git
synced 2025-07-24 02:31:24 +00:00
.vscode
assets
components
config
docs
framework
lib
click-outside
click-outside.tsx
has-parent.js
index.ts
is-in-dom.js
hooks
colors.ts
defaults.ts
focus-trap.tsx
get-slug.ts
range-map.ts
search.tsx
to-pixels.ts
usage-warns.ts
pages
public
.editorconfig
.env.template
.gitignore
.prettierignore
README.md
codegen.json
commerce.config.json
global.d.ts
license.md
next-env.d.ts
next.config.js
package.json
postcss.config.js
tailwind.config.js
tsconfig.json
yarn.lock
43 lines
938 B
TypeScript
43 lines
938 B
TypeScript
import React, { useRef, useEffect, 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) => {
|
|
const innerRef = useRef()
|
|
|
|
const handleClick = (event: any) => {
|
|
if (!hasParent(event.target, innerRef?.current)) {
|
|
if (typeof onClick === 'function') {
|
|
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: innerRef })
|
|
}
|
|
|
|
export default ClickOutside
|