Last active
July 7, 2018 20:32
-
-
Save jonathanharrell/f4d6bd9651bceffa5fce588c6cad5ac7 to your computer and use it in GitHub Desktop.
ObserveDimensions ReactComponent Using Render Props
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
class ObserveDimensions extends React.Component { | |
constructor(props) { | |
super(props) | |
this.state = { | |
width: null, | |
height: null | |
} | |
this.elementToObserve = React.createRef() | |
} | |
componentDidMount(nextProps) { | |
const erd = elementResizeDetectorMaker({ strategy: 'scroll' }) | |
erd.listenTo(this.elementToObserve.current, element => { | |
this.setState({ | |
width: element.offsetWidth, | |
height: element.offsetHeight | |
}) | |
}); | |
} | |
render() { | |
return ( | |
<div className="observed-element" ref={this.elementToObserve}> | |
{this.props.render({ | |
width: this.state.width, | |
height: this.state.height | |
})} | |
</div> | |
) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment