File size: 1,100 Bytes
1e92f2d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
// @flow

import * as React from "react";

type Props = {|
  +children: ({| +setElementRef: (el: ?HTMLElement) => mixed |}) => React.Node,
  +onOutsideClick: () => void,
|};

/**
 * A helper to help you do something when a user clicks outside of a component
 */
class ClickOutside extends React.PureComponent<Props, void> {
  elementRef: ?HTMLElement;

  componentDidMount = (): void => {
    document.addEventListener("mousedown", this.handleOutsideOnClick, false);
  };

  componentWillUnmount = (): void => {
    document.removeEventListener("mousedown", this.handleOutsideOnClick, false);
  };

  setElementRef = (el: ?HTMLElement): mixed => {
    if (el) this.elementRef = el;
  };

  isOutsideClick = (target: mixed) =>
    this.elementRef &&
    target instanceof Node &&
    !this.elementRef.contains(target);

  handleOutsideOnClick: MouseEventListener = ({ target }) => {
    if (this.isOutsideClick(target)) this.props.onOutsideClick();
  };

  render() {
    const { children } = this.props;
    return children({ setElementRef: this.setElementRef });
  }
}

export default ClickOutside;