All files / outside-click-handler/src index.js

87.5% Statements 14/16
50% Branches 4/8
100% Functions 6/6
100% Lines 14/14
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 45 46 47 48 49 50 51                              5x   5x 5x       6x   6x       1x   1x       1x 1x 1x 1x 1x         1x       5x      
/* @flow */
 
import * as React from 'react';
 
type Props = {
  children: React.Node,
  onOutsideClick: Function,
};
 
export default class OutsideClickHandler extends React.Component<Props, void> {
  childNode: ?HTMLElement;
  onOutsideClick: Function;
  setChildNodeRef: Function;
 
  constructor(props: Props) {
    super(props);
 
    this.onOutsideClick = this.onOutsideClick.bind(this);
    this.setChildNodeRef = this.setChildNodeRef.bind(this);
  }
 
  componentDidMount() {
    Iif (!document.body) return;
 
    document.body.addEventListener('click', this.onOutsideClick);
  }
 
  componentWillUnmount() {
    Iif (!document.body) return;
 
    document.body.removeEventListener('click', this.onOutsideClick);
  }
 
  onOutsideClick(e: Event) {
    const { onOutsideClick } = this.props;
    const { childNode } = this;
    const isDescendantOfRoot = childNode && childNode.contains((e.target: any));
    Eif (!isDescendantOfRoot) {
      onOutsideClick();
    }
  }
 
  setChildNodeRef(ref: ?HTMLElement) {
    this.childNode = ref;
  }
 
  render() {
    return <div ref={this.setChildNodeRef}>{this.props.children}</div>;
  }
}