I'm trying to make a menu and that when pressing outside of it it will get closed and will active clearTimeout so it won't get close again if re-opened.
Somehow when I press on the menu this condition is always true -
if (document.activeElement !== menuRef.current) {//document.activeElement.id !== 'myField'
<div ref={menuRef} id="myField"> is the wrapping div of the menu
So it doesn't work.
What am I doing here wrong ?
All in the codesandbox - Codesandbox
export default function Example() {
const { toggleMenu } = useMenuState({ transition: true });
let closeTimeMenu;
const menuRef = useRef(null);
useEffect(() => {
function handleClickOutside() {
setTimeout(() => {
if (document.activeElement !== menuRef.current) {//document.activeElement.id !== 'myField'
console.log(" !== menuRef");
clearTimeout(closeTimeMenu);
window.onclick = toggleMenu(false);
}
}, 500);
}
document.addEventListener("mousedown", handleClickOutside);
return () => {
document.removeEventListener("mousedown", handleClickOutside);
};
}, []);
function handleClick() {
//menuRef.current.focus(); or -
document.getElementById('myField').focus();
}
function timeout() {
closeTimeMenu = setTimeout(function () {
toggleMenu(false);
}, 1500);
}
return (
<div ref={menuRef} id="myField">
<button
onMouseEnter={() => {
toggleMenu(true);
clearTimeout(closeTimeMenu);
}}
onMouseLeave={() => timeout()}
>
Hover to Open
</button>
<ControlledMenu
anchorRef={menuRef}
onMouseEnter={() => {
toggleMenu(true);
clearTimeout(closeTimeMenu);
}}
onItemClick={() => {
handleClick();
toggleMenu(false);
}}
onMouseLeave={() => timeout()}
>
<MenuItem>Save</MenuItem>
<MenuItem>Close Window</MenuItem>
</ControlledMenu>
</div>
);
}
Thanks