9
<parent onBlur={function}>
  <child>
    <child>
    </child>
  </child>
</parent>

In a structure like this, I want to catch if parent element loses focus or not. I want to fire that behavior when clicked outside of the parent div. However, parent element loses its focus when I click child element as well. You can think this structure as dropdown menu. Is there a way to achieve this inside of the stateless react component? I cannot use jquery or other libraries.

wolf
  • 399
  • 1
  • 6
  • 19

1 Answers1

0

This can be achieved with mouse events.

If the user clicks on the screen we can check if the click is inside or outside the component and treat it as Focus event to blur event.

  • Click Inside - Focus
  • Click Outside - Blur

function Parent(props){
  const ref = useRef();
  
  useEffect(()=>{
  
    document.addEventListener("mousedown", checkFocus.bind(this))
    return ()=>{
      document.removeEventListener("mousedown", checkFocus.bind(this))
    }
  },[])
  
  const checkFocus = (event)=>{
    if(ref.current && !ref.current.contains(event.target) && props.onBlur)
      props.onBlur()
  }
  
  return (
    <div ref={ref}>
      {props.children}
    </div>
  );
  
}

function Child(){

  return (
    <h1>child</h1>
  );

}

function Main(){

  return (
    <Parent onBlur={()=>{ console.log("focus lost.") }}>
      <Child>
        <Child>
        </Child>
      </Child>
    </Parent>
  );

}