useOutsideClick
useOutsideClick
is a custom hook that detects click events outside of an element.
const ref = useRef<HTMLDivElement>(null)
const { open, onOpen, onClose } = useDisclosure()
useOutsideClick({
ref,
handler: onClose,
})
return (
<>
{open ? (
<Center ref={ref} h="10" px="3" bg="danger" color="white" rounded="l2">
Hey, Click anywhere outside of me to close.
</Center>
) : (
<Button onClick={onOpen}>Please Click</Button>
)}
</>
)
If you use this code, you need to add
"use client"
to the top of the file.Usage
import { useOutsideClick } from "@yamada-ui/react"
import { useOutsideClick } from "@/components/ui"
import { useOutsideClick } from "@workspaces/ui"
const { open, onOpen, onClose } = useDisclosure()
useOutsideClick({
ref,
handler: onClose,
})