react hook to handle outside click events
You can install the module via npm
or yarn
:
npm i use-dom-outside-click --save
yarn add use-dom-outside-click
import { useOutsideClick } from 'use-dom-outside-click';
const [isPanelOpen, setIsPanelOpen] = useState(false)
const triggerRef = useRef<HTMLButtonElement>();
const panelRef= useRef<HTMLDivElement>();
// third argument is optional
useOutsideClick(panelRef, () => setIsPanelOpen(false), [triggerRef]);
const handleClick = () => {
setIsPanelOpen(open => !open)
}
<Popover>
<Popover.Button ref={triggerRef} onClick={handleClick}>
// button code
</Popover.Button>
<Popover.Panel ref={panelRef} isOpen={isPanelOpen}>
// panel code
</Popover.Panel>
</Popover>
useOutsideClick(elementRef, callback, [...exceptionsRefs]);
elementRef
- reference of the element from which you want to detect the outside clickcallback
- function to execute when clicked outside the elementexceptionsRefs
(optional) - array of references in which you want to prevent the callback from being executed if they are clicked