Created
August 30, 2018 11:51
-
-
Save tol-is/75b82c02cff9f7a1b9f927295a253523 to your computer and use it in GitHub Desktop.
with-size higher order function.
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
import React, { Component } from 'react'; | |
import { debounce } from 'throttle-debounce'; | |
export default function (ComposedComponent) { | |
class WithSize extends Component { | |
static getDomNodeDimensions(node) { | |
const { | |
top, right, bottom, left, width, height, | |
} = node.getBoundingClientRect(); | |
return { | |
top, right, bottom, left, width, height, | |
}; | |
} | |
constructor() { | |
super(); | |
this.debounceUpdate = debounce(100, this.update); | |
this.state = { | |
width : 0, | |
}; | |
} | |
componentDidMount() { | |
window.addEventListener('resize', this.debounceUpdate); | |
this.update(); | |
} | |
componentWillUnmount() { | |
window.removeEventListener('resize', this.debounceUpdate); | |
} | |
update = () => { | |
const clientRect = WithSize.getDomNodeDimensions(this.node); | |
this.setState({ | |
...clientRect, | |
}); | |
} | |
render() { | |
return ( | |
<div ref={node => { this.node = node; }} style={{ width : '100%', display : 'block' }}> | |
{this.state.width ? <ComposedComponent {...this.state} {...this.props} /> : null} | |
</div> | |
); | |
} | |
} | |
return WithSize; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment