useDismiss
Executes callback when a keydown event involving the Escape key or a pointerdown event
occurs outside of passed ref element. Useful when creating components, like dialogs, popovers,
dropdowns, etc., that should be dismissed when the user interacts outside of them.
- @param
ref- Element reference to base events on. - @param
callback- Callback to execute when akeydownorpointerdownevent occurs. - @param
options- Configurable options
Example
const ref = useRef<HTMLDivElement>(null)
const [isOpen, setIsOpen] = useState(false)
useDismiss(ref, () => setIsOpen(false), { when: isOpen })
return (
<>
<button type="button" onClick={() => setIsOpen(true)}>Open</button>
{isOpen && (<div ref={ref}>Content</div>)}
</>
)