Home > Blockchain >  Click outside drop-down and close drop-down react
Click outside drop-down and close drop-down react

Time:10-04

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

CodePudding user response:

    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])
  • Related