Skip to content

Instantly share code, notes, and snippets.

@kyleshevlin
Created October 25, 2016 18:24
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/1b383d39e10a1e15096c4007e890751d to your computer and use it in GitHub Desktop.
Save kyleshevlin/1b383d39e10a1e15096c4007e890751d to your computer and use it in GitHub Desktop.
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