useClickOutside Hook
Clicking outside a referential element will close it. This hook is useful for dropdowns, modals, etc. To use it you must import useRef and create a variable named 'wrapperRef' with a value of 'useRef(null)'. You then attach 'ref={wrapperRef} to the element you'd like the user to click outside of. To close the element, create a 'closeInput' function sets state to the desired value.
import { useEffect } from 'react';
const useClickOutside = (ref, closeInput) => {
useEffect(() => {
function handleClickOutside(e) {
if (ref.current && !ref.current.contains(e.target)) {
closeInput();
// stopPropagation is optional -- remove if breaking
e.stopPropagation();
}
}
document.addEventListener('mousedown', handleClickOutside);
return () => {
document.removeEventListener('mousedown', handleClickOutside);
};
}, [ref]);
};
export default useClickOutside;