Detect click outside of the box (ReactJS Hooks)
import React, { useEffect, useRef } from "react";
import { Link } from "react-router-dom";
const UserOptionsMenu = ({ openMenu }) => {
const popover = useRef(null);
const handleClick = e => {
if (popover.current && !popover.current.contains(e.target)) {
openMenu();
}
};
useEffect(() => {
document.addEventListener("click", handleClick, false);
return () => {
document.removeEventListener("click", handleClick, false);
};
}, []);
return (
<div ref={popover}>
<ul>
<li>Settings</li>
<Link to="/logout">
<li>Logout</li>
</Link>
</ul>
</div>
);
};
export default UserOptionsMenu;