Skip to content

Instantly share code, notes, and snippets.

@juliankrispel
Created October 18, 2018 14:24
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 juliankrispel/4f18acc36b7597215219c4132e4fbd60 to your computer and use it in GitHub Desktop.
Save juliankrispel/4f18acc36b7597215219c4132e4fbd60 to your computer and use it in GitHub Desktop.
Simple Render Prop component to poll element measurements
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