Created
October 18, 2018 14:24
-
-
Save juliankrispel/4f18acc36b7597215219c4132e4fbd60 to your computer and use it in GitHub Desktop.
Simple Render Prop component to poll element measurements
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, { PureComponent } from 'react' | |
/* | |
* PollBounds | |
* render with referenced element measurements | |
* @param measureRef: React.Ref | |
* @param pollTime: number - polling time for polling client rect | |
* @param children({ bounds }) | |
*/ | |
export default class ClientRect extends PureComponent { | |
static defaultProps = { | |
pollTime: 300, | |
measureRef: null | |
} | |
componentDidMount() { | |
const { pollTime } = this.props | |
this._interval = setInterval(this.pollBounds, pollTime) | |
} | |
componentWillUnmount() { | |
clearInterval(this._interval) | |
} | |
pollBounds = () => { | |
const { measureRef } = this.props | |
if(measureRef.current) { | |
const { top, left, bottom, right, height, width } = measureRef.current.getBoundingClientRect() | |
this.setState({ top, left, bottom, right, height, width }) | |
} | |
} | |
render() { | |
return this.props.children(this.state) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment