Skip to content

Instantly share code, notes, and snippets.

@poeticninja
Last active March 21, 2017 23:44
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 poeticninja/3bff3b1f1fbd2709b865f4ce18607481 to your computer and use it in GitHub Desktop.
Save poeticninja/3bff3b1f1fbd2709b865f4ce18607481 to your computer and use it in GitHub Desktop.
React component width decorator.
import React from "react";
import elementResizeEvent from "element-resize-event";
export default (Component) => {
class ComponentWidth extends React.Component {
state = {
width: 0,
};
componentDidMount() {
const element = this.targetElement;
const self = this;
if (element) {
self.updateComponentWidth(element.offsetWidth);
elementResizeEvent(element, () => {
self.updateComponentWidth(element.offsetWidth);
});
}
}
updateComponentWidth(width) {
this.setState({ width });
}
render() {
return (
<div
class="element-resize-event-detector"
ref={(element) => {
this.targetElement = element;
}}
>
{this.state.width || this.props.width ? (
<Component width={this.state.width} {...this.props} />
) : null }
</div>
);
}
}
return ComponentWidth;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment