The useClickOutside
hook allows one to listen for clicks outside of an element
(passed in as a ref
) and if the when
condition is true, to execute.
Usage
import React, { useRef, useState } from "react"
import { useClickOutside, Box } from "@artsy/palette"
const Banner = ({ isVisible }) => {
const bannerRef = useRef()
const [hide, setHidden] = useState(false)
useClickOutside({
ref: bannerRef,
onClickOutside: () => setHidden(true),
when: isVisible,
type: "click",
})
return (
<Box ref={bannerRef} display={hide ? "none" : "block"}>
...
</Box>
)
}