Skip to content

Instantly share code, notes, and snippets.

@tol-is
Created August 30, 2018 11:51
Show Gist options
  • Save tol-is/75b82c02cff9f7a1b9f927295a253523 to your computer and use it in GitHub Desktop.
Save tol-is/75b82c02cff9f7a1b9f927295a253523 to your computer and use it in GitHub Desktop.
with-size higher order function.
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