DeepakD
Reactiflux4y ago
4 replies
Deepak

Deepak – 06-27 Sep 2

hi, I am using the following code to focus my auto search suggestion box. it works as expected.
If user click outside the search result container it will hide the container.
However it only target the document and not the entire screen for ex if i click on browser tabs or address bar it won't work
 useEffect(() => {
    //hide showSuggestion if the user clicked outside of the ref
    const handleClickOutside = (event) => {
      if (
        searchSuggestionRef.current &&
        !searchSuggestionRef.current.contains(event.target)
      ) {
        setShowSuggestions(false);
      }
    };
    document.addEventListener("mousedown", handleClickOutside);
    return () => {
      document.removeEventListener("mousedown", handleClickOutside);
    };
  }, [searchSuggestionRef]);

I have tried
window.addEventListener("mousedown", handleClickOutside);

but it doesn't work
Was this page helpful?