React hook to execute callback when a click is happened outside of component.
Install
yarn add use-click-outside-close
Usage
import React, { useRef, useState } from 'react';
import useClickOutside from 'use-click-outside';
const Modal = ({ onClose }) => {
const [toggle, setToggle] = useState(false);
const ref = useRef();
useClickOutside(ref, () => setOpneModal(false));
return <Modal ref={ref}>Hello!</Modal>;
};
Or if you need a custom event type instead of default 'click', third parameter can be passed:
useClickOutside(ref, handler);