score:1

Accepted answer
useEffect(() => {
  const outsideClickHandler = (e) => {
    if (props.showDropdown && !outsideRef.current?.contains(e.target)) {
      props.onSelectItem(false);
    }
  };

  window.addEventListener("click", outsideClickHandler);

  return () => window.removeEventListener("click", outsideClickHandler);
}, [props]);

...

<div
  ref={outsideRef}
  ...
>
  ...
</div>

score:3

const ref = useRef();

...

useEffect(() => {
    document.addEventListener("click", handleDropdownClick);
  }, [ref]);

const handleDropdownClick = (e) => {
    e.stopPropagation();
    if (ref.current && ref.current.contains(e.target)) {
      setShowDropdown(true);
    } else {
      setShowDropdown(false);
    }
  };

...

<span
     ref={ref}
     className="custm-dropdown"
     onClick={handleDropdownClick}
 >

Related Query

More Query from same tag