Handle outside click for options
The option display should disappear (removed from the DOM altogether) when the user clicks anywhere on the outside.
To do this, let us point a ref to the outermost div of the component and add an eventListener to the window object. If the mouseDown event appears on the window and the event.target is not the ref we created, shouldDisplayOptions will be set to false.
const wrapperRef = useRef(null);
useEffect(() => {
window.addEventListener("mousedown", handleClickOutside);
});
const handleClickOutside = event => {
const wrapper = wrapperRef.current;
if (wrapper && !wrapper.contains(event.target)) {
setShouldDisplayOptions(false);
}
};
return (
<div ref={wrapperRef} className="flex-container flex-column pos-rel">
{ /* rest of the code */ }
</div>
)
But, there is an issue. In this scenario, even if the component is unmounted, the window object will have the reference of the eventListener that we attached to it. This will cause a memory leak in our application, that we never want as it will make our app non-performant eventually.
How to solve this?
useEffect React hook also provides a cleanup function, which is similar to componentWillUnmount lifecycle method in Class components.
The code inside useEffect will change to
useEffect(() => {
window.addEventListener("mousedown", handleClickOutside);
return () => {
window.removeEventListener("mousedown", handleClickOutside);
};
});
Handling the outside click will make your component behave like this
.gif)
The final code can be found here
4
