Advertisement
danine1

Event listener - OutsideClickHandler

Mar 8th, 2018
330
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. import React from "react";
  2. import PropTypes from "prop-types";
  3.  
  4. class OutsideClickHandler extends React.Component {
  5.   static propTypes = {
  6.     children: PropTypes.node,
  7.     className: PropTypes.string,
  8.     onOutsideClick: PropTypes.func,
  9.   };
  10.  
  11.   static defaultProps = {
  12.     children: null,
  13.     className: null,
  14.     onOutsideClick: null,
  15.   };
  16.  
  17.   componentDidMount() {
  18.     const { onOutsideClick } = this.props;
  19.     document.addEventListener(
  20.       "mousedown",
  21.       this.handleClickOutside(onOutsideClick),
  22.     );
  23.   }
  24.  
  25.   componentWillReceiveProps(nextProps) {
  26.     if (nextProps.onOutsideClick !== this.props.onOutsideClick) {
  27.       // Remove previous listener
  28.       document.removeEventListener(
  29.         "mousedown",
  30.         this.handleClickOutside(this.props.onOutsideClick),
  31.       );
  32.       // Attach the new listener
  33.       document.addEventListener(
  34.         "mousedown",
  35.         this.handleClickOutside(nextProps.onOutsideClick),
  36.       );
  37.     }
  38.   }
  39.  
  40.   componentWillUnmount() {
  41.     // Remove the last listener
  42.     const { onOutsideClick } = this.props;
  43.     document.removeEventListener(
  44.       "mousedown",
  45.       this.handleClickOutside(onOutsideClick),
  46.     );
  47.   }
  48.  
  49.   setRef = (node) => {
  50.     this.componentRef = node;
  51.   };
  52.  
  53.   handleClickOutside = onOutSideClick => (event) => {
  54.     if (
  55.       this.componentRef &&
  56.       !this.componentRef.contains(event.target) &&
  57.       typeof onOutSideClick === "function"
  58.     ) {
  59.       onOutSideClick();
  60.     }
  61.   };
  62.  
  63.   render() {
  64.     const { children, className, ...rest } = this.props;
  65.     return (
  66.       <div ref={this.setRef} className={className} {...rest}>
  67.         {children}
  68.       </div>
  69.     );
  70.   }
  71. }
  72. export default OutsideClickHandler;
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement