Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Typescript – mouse click outside div type

I need to specify event type. Anyone can help with right type exept any, unknown ?

useEffect(() => {
    const checkIfClickedOutside = (event: any) => {
      if (
        isOpened &&
        selectRef.current &&
        !selectRef.current.contains(event.target)
      ) {
        setIsOpened(false);
      }
    };

    document.addEventListener("mousedown", checkIfClickedOutside);

    return () => {
      document.removeEventListener("mousedown", checkIfClickedOutside);
    };
  }, [isOpened]);

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

You should be able to use the MouseEvent.

useEffect(() => {
    const checkIfClickedOutside = (event: MouseEvent) => {
      if (
        isOpened &&
        selectRef.current &&
        !selectRef.current.contains(event.target)
      ) {
        setIsOpened(false);
      }
    };

    document.addEventListener("mousedown", checkIfClickedOutside);

    return () => {
      document.removeEventListener("mousedown", checkIfClickedOutside);
    };
  }, [isOpened]);

Do you really need to use mousedown?
It looks like you want to close a div, when clicking outside. I would suggest, that you use click instead, as it gives the user the ability to cancel their action by performing the mouseup outside of the targeted area.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading