all files / src/ index.js

95.65% Statements 66/69
94.59% Branches 35/37
94.44% Functions 17/18
85.71% Lines 18/21
5 statements, 13 branches Ignored     
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 52 53 54 55 56 57 58 59 60 61 62 63 64                                                                                              
import {PropTypes, Component} from 'react';
 
function on(element, type, callback) {
  Eif (element.addEventListener) {
    element.addEventListener(type, callback);
  } else { // IE8+ Support
    element.attachEvent(`on${type}`, () => {
      callback.call(element);
    });
  }
}
 
function off(element, type, callback) {
  Eif (element.removeEventListener) {
    element.removeEventListener(type, callback);
  } else { // IE8+ Support
    element.detachEvent(`on${type}`, callback);
  }
}
 
function listenersForEach(props, callback) {
  const {
    elementName,
    ...other,
  } = props;
 
  const element = window[elementName];
 
  for (const eventIdentifier in other) {
    const eventName = eventIdentifier.substring(2).toLowerCase();
 
    callback(element, eventName, other[eventIdentifier]);
  }
}
 
export default class EventListener extends Component {
  static propTypes = {
    /**
     * You can provide a children too.
     */
    children: PropTypes.node,
    /**
     * Name of the element that we will be listening to.
     */
    elementName: PropTypes.string,
  };
 
  componentDidMount() {
    listenersForEach(this.props, (element, eventName, callback) => {
      on(element, eventName, callback);
    });
  }
 
  componentWillUnmount() {
    listenersForEach(this.props, (element, eventName, callback) => {
      off(element, eventName, callback);
    });
  }
 
  render() {
    return this.props.children || null;
  }
}