Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Reusable ResizeListener React Component

Reusable ResizeListener React Component

Usage

Include the ResizeListener component anywhere you need to listen to the resize event. Then pass a function into the resizeHandler 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 ResizeListener = React.createClass({
propTypes: {
resizeHandler: func.isRequired
},
render () {
return <div className='resize_listener' />
},
componentDidMount () {
this.bindResize()
},
componentWillUnmount () {
this.unbindResize()
},
bindResize () {
window.addEventListener('resize', this.props.resizeHandler)
},
unbindResize () {
window.removeEventListener('resize', this.props.resizeHandler)
}
})
module.exports = ResizeListener
const React = require('react')
const ResizeListener = require('./ResizeListener')
const ResizeListenerExample = React.createClass({
render () {
return (
<div>
<ResizeListener resizeHandler={() => { console.log('resizing') }} />
</div>
)
}
})
module.exports = ResizeListenerExample
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment