React - capture click outside component

  1. 1. Use case
  2. 2. Handy instructions
    1. 2.1 Create a ref to div
    2. 2.2 Add event listener

1. Use case

Suppose you create your own pop up modal, or you invent your own dropdown, you will need to deal/ capture with click outside of the component. This blog will illustrate how to do so.

2. Handy instructions

2.1 Create a ref to div

render() {
    return (
        <div ref = {node => this.node = node}> </div>
    );
}

2.2 Add event listener

componentWillMount() {
    document.addEventListener('mousedown', this.handleClick, false);
}

componentWillUnmount() {
    document.removeEventListener('mousedown', this.handleClick, false);
}

handleClick = (e) => {
    if (this.node.contains(e.target)) {
        // inside this component, do whatever you want
        return;
    }

    // handle outside click
    this.handleOutsideClick();
}

转载请注明来源,欢迎对文章中的引用来源进行考证,欢迎指出任何有错误或不够清晰的表达。可以在下面评论区评论,也可以邮件至 stone2paul@gmail.com

文章标题:React - capture click outside component

文章字数:102

本文作者:Leilei Chen

发布时间:2020-01-30, 23:19:07

最后更新:2020-02-01, 22:06:57

原始链接:https://www.llchen60.com/React-capture-click-outside-component/

版权声明: "署名-非商用-相同方式共享 4.0" 转载请保留原文链接及作者。

目录
×

喜欢就点赞,疼爱就打赏