One of the best user experience additions to a menu, is closing that menu when a user clicks outside of it. When a drop down opens, and the one way to close it is selecting another drop down or clicking a x, it drives me nuts. The thing that I want to do is click outside of it, as I tap off that menu.
Here is a example of how to use a
useEffecthook to handle this. The
useEffectruns every time the component renders. It checks if the click event is part of the current reference, and if it the target of the event is contained within. If it fails this check, it closes the menu by setting
Other things that you can do for menus that focus trap, is to allow escape the close the menu. This improves the accessibility for keyboard users, but it also allows the user to use the built in control for this. After all it’s called the “Escape” key.