Home > Back-end >  reactjs - Close menu children on click outside
reactjs - Close menu children on click outside

Time:10-11

I have this simple sandbox: https://codesandbox.io/s/priceless-sun-mtkcrj?file=/src/Menu.tsx

Basically a search dialogue box will appear once I click on the menu button and closes if I clicked anything outside of those. I currently have a custom hook to detect if I clicked outside.

function useOuterClick(callback: any) {
  const callbackRef = useRef<any>(); // initialize mutable ref, which stores callback
  const innerRef = useRef<any>(); // returned to client, who marks "border" element

  // update cb on each render, so second useEffect has access to current value
  useEffect(() => {
    callbackRef.current = callback;
  });

  useEffect(() => {
    function handleClick(e: any) {
      if (
        innerRef.current &&
        callbackRef.current &&
        !innerRef.current.contains(e.target)
      )
        callbackRef.current(e);
    }
    document.addEventListener("click", handleClick);
    return () => document.removeEventListener("click", handleClick);
  }, []); // no dependencies -> stable click listener

  return innerRef; // convenience for client (doesn't need to init ref himself)
}

However the current behaviour is that the entire dialogue box is closed once I click on it. I am confused as I was expecting it to remain open since its a child of the parent ref. I tried to add an another ref to the child div and add some logic to the callback condition something like:

const childRef = useRef(null);
const parentRef =  useOuterClick(() => {
   if (document.activeElement !== childRef.current) setClicked(false)
});

But nothing seems to change.

How would I fix this behaviour?

CodePudding user response:

Just use event.stopPropagation. When you click inner div it will prevent the close.

https://developer.mozilla.org/en-US/docs/Web/API/Event/stopPropagation

CodePudding user response:

Why not useState and control this feature

  • Related