Clicking outside of the menu does not close a controlled menu
I'm using this example to use a controlled select component. https://github.com/JedWatson/react-select/blob/master/docs/examples/ControlledMenu.tsx
The menu does not close when clicking outside of the menu. I can see the browser that the document.activeElement is just the body of the page. I've tried setting focus to the select component on menu open so that I can hook into the onBlur but the body of the page is still focused.
I also had the same requirement, although for the element inspection you can use following option in Chrome:
but problem with this, clicking anywhere in document (but not in the dev section tool) will be closing the menu ( which we don't want), here is the code snippet that works for me ( simple hack, but works):
...
const [isMenuActuallyOpen, setIsMenuActuallyOpen] = useState(false);
...
useEffect(() => {
const selectElement = selectInstanceRef.current;
// Remember to get the MenuListRef when when `menuIsOpen = true`
const menuListElement: HTMLDivElement | null | undefined = selectElement?.menuListRef
const handleSelectMenuMouseDown = (e: MouseEvent) => {
setIsMenuActuallyOpen(true);
// Preventing & stopping the propagation will not cause any issue
e.preventDefault();
e.stopPropagation();
}
menuListElement && menuListElement.addEventListener("mousedown", handleSelectMenuMouseDown);
return () => {
menuListElement && menuListElement.removeEventListener("mousedown", handleSelectMenuMouseDown);
}
}, [isMenuActuallyOpen]);
...
return (
<Select ref={selectInstanceRef as any} menuIsOpen={isMenuActuallyOpen} {...otherPropsOrEvents}/>
)