Skip to content

Instantly share code, notes, and snippets.

@kyleshevlin
Last active Oct 25, 2016
Embed
What would you like to do?
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