Search code examples
javascriptreactjsmouseevent

Click outside drop-down and close drop-down react


I have a demo App and want to close the drop-down when click anywhere outside.

Just a simple code.

Here is my demo app link of codesandbox

Click Here


Solution

  •     useEffect(() => {
        const checkIfClickedOutside = e => {   
          if (toggle && dropDownRef.current && !dropDownRef.current.contains(e.target)) {
            setToggle(false)
          }
        }
        document.addEventListener("mousedown", checkIfClickedOutside)
    
        return () => {
          document.removeEventListener("mousedown", checkIfClickedOutside)
        }
      }, [toggle])