Skip to content

Instantly share code, notes, and snippets.

@kyleshevlin
Last active October 25, 2016 18:21
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kyleshevlin/75de0f3a1dd5252b2367edfa9996d24d to your computer and use it in GitHub Desktop.
Save kyleshevlin/75de0f3a1dd5252b2367edfa9996d24d to your computer and use it in GitHub Desktop.
Reusable ScrollListener React Component

Reusable ScrollListener React Component

Usage

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.

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
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