0
votes

I am using useRef to define when a click event happens, and if outside a search input I set not focuses (which makes a results container hide) and some specific styling.

This generally works, however i added a clear input button, with ref searchClear. The issue is, because this is on top of the wrapper ref it sees a click on this as not a click on the wrapper, and im not sure the logic how to resolve.

The issue with the code below is that i also hide the clear button when there is no text input. So setWhatFocused(false); triggers when i have some input and the results container shows/hides when click anywhere. But if there is no input (therefore no clear button) then (searchClear.current && !searchClear.current.contains(e.target)) fails.

const wrapper = useRef(null);
const searchInput = useRef(null);
const searchClear = useRef(null);

useEffect(() => {
  document.addEventListener("click", handleClickOutside, false);
  return () => {
    document.removeEventListener("click", handleClickOutside, false);
  };
}, []);

const handleClickOutside = (e) => {
  if (wrapper.current && !wrapper.current.contains(e.target)) {

    if (searchClear.current && !searchClear.current.contains(e.target)) {
      setWhatFocused(false);
    }

  }
};

I tried to add the below but it loses the focused style.

if (!searchClear.current){
    setWhatFocused(false);
}

Hopefully i have added enough detail to explain.

The simple way to solve is the answer to any of the following questions:

Can i detect click when one ref is on top top of the ref i need to detect? Can i use the same ref several times without issues down line (if i can at all)?

Failing positive answers to above, any suggestions?

1

1 Answers

0
votes

I didn't find an exact solution, but in the end i changed it so the element was made visibility: hidden and toggled that instead of the actual element being conditionally rendered.