Detect click outside React component

后端 未结 30 1228
日久生厌
日久生厌 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:10

    None of the other answers here worked for me. I was trying to hide a popup on blur, but since the contents were absolutely positioned, the onBlur was firing even on the click of inner contents too.

    Here is an approach that did work for me:

    // Inside the component:
    onBlur(event) {
        // currentTarget refers to this component.
        // relatedTarget refers to the element where the user clicked (or focused) which
        // triggered this event.
        // So in effect, this condition checks if the user clicked outside the component.
        if (!event.currentTarget.contains(event.relatedTarget)) {
            // do your thing.
        }
    },
    

    Hope this helps.

提交回复
热议问题