Detect click outside React component

后端 未结 30 1662
日久生厌
日久生厌 2020-11-22 13:54

I\'m looking for a way to detect if a click event happened outside of a component, as described in this article. jQuery closest() is used to see if the target from a click e

30条回答
  •  礼貌的吻别
    2020-11-22 14:15

    I had a case when I needed to insert children into the modal conditionally. Something like this, bellow.

    const [view, setView] = useState(VIEWS.SomeView)
    
    return (
        
          {VIEWS.Result === view ? (
             setView(VIEWS.Details)} />
          ) : VIEWS.Details === view ? (
            
    setView(VIEWS.Result) /> /> ) : null} )

    So !parent.contains(event.target) doesn't work here, because once you detach children, parent (modal) doesn't contain event.target anymore.

    The solution I had (which works so far and have no any issue) is to write something like this:

    const listener = (event: MouseEvent) => {
       if (parentNodeRef && !event.path.includes(parentNodeRef)) callback()
    }
    

    If parent contained element from already detached tree, it wouldn't fire callback.

    EDIT: event.path is new and doesn't exit in all browsers yet. Use compoesedPath instead.

提交回复
热议问题