Created
January 24, 2019 08:54
-
-
Save satour/c01970569a63c30bfdf2de3152fc0d8c to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import React from 'react'; | |
import PropTypes from 'prop-types'; | |
export default class EventListener extends React.Component { | |
componentDidMount() { | |
this.getListeners().forEach( ( [ type, listener ] ) => { | |
this.props.eventTarget.addEventListener( type, listener ); | |
} ); | |
} | |
componentWillUnmount() { | |
this.getListeners().forEach( ( [ type, listener ] ) => { | |
this.props.eventTarget.removeEventListener( type, listener ); | |
} ); | |
} | |
getListeners() { | |
return Object | |
.keys( this.props ) | |
.filter( key => key.startsWith( 'on' ) ) | |
.map( key => [ key.slice( 2 ).toLowerCase(), this.props[key] ] ); | |
} | |
render() { | |
return null; | |
} | |
} | |
EventListener.propTypes = { | |
eventTarget: PropTypes.object.isRequired, | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment