Last active
March 21, 2017 23:44
-
-
Save poeticninja/3bff3b1f1fbd2709b865f4ce18607481 to your computer and use it in GitHub Desktop.
React component width decorator.
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 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