Include the ScrollListener
component anywhere you need to listen to the scroll event. Then pass a function into the scrollHandler
prop. This is a required prop. Because you include this component in other components, the function you pass has access to any props or state of that component.
Last active
October 25, 2016 18:21
-
-
Save kyleshevlin/75de0f3a1dd5252b2367edfa9996d24d to your computer and use it in GitHub Desktop.
Reusable ScrollListener React Component
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
const React = require('react') | |
const { func } = React.PropTypes | |
const ScrollListener = React.createClass({ | |
propTypes: { | |
scrollHandler: func.isRequired | |
}, | |
render () { | |
return <div className='scroll_listener' /> | |
}, | |
componentDidMount () { | |
this.bindScroll() | |
}, | |
componentWillUnmount () { | |
this.unbindScroll() | |
}, | |
bindScroll () { | |
document.addEventListener('touchmove', this.props.scrollHandler) | |
window.addEventListener('scroll', this.props.scrollHandler) | |
}, | |
unbindScroll () { | |
document.removeEventListener('touchmove', this.props.scrollHandler) | |
window.removeEventListener('scroll', this.props.scrollHandler) | |
} | |
}) | |
module.exports = ScrollListener |
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
const React = require('react') | |
const ScrollListener = require('./ScrollListener') | |
const ScrollListenerExample = React.createClass({ | |
render () { | |
return ( | |
<div> | |
<ScrollListener scrollHandler={() => { console.log('scrolling') }} /> | |
</div> | |
) | |
} | |
}) | |
module.exports = ScrollListenerExample |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment