Skip to content

Instantly share code, notes, and snippets.

@ronnyhaase
Created August 24, 2018 11:50
Show Gist options
  • Save ronnyhaase/0f6d262735574193d13c81d73f140776 to your computer and use it in GitHub Desktop.
Save ronnyhaase/0f6d262735574193d13c81d73f140776 to your computer and use it in GitHub Desktop.
A React component passing it's width and height to it's children
// Passes it's width and height to it's children
//
// Does *not* care for resize, since this event is only fired by root element.
// Could either listen to itself, or get notified by a provider to reduce
// listeners
class DimensionPasser extends Component {
constructor(props) {
super(props)
this.state = { parentWidth: 0, parentHeight: 0 }
this.wrapperRef = React.createRef()
}
componentDidMount() {
this.setState({
width: this.wrapperRef.current.clientWidth,
height: this.wrapperRef.current.clientHeight
})
}
render() {
const childrenWithProps = React.Children.map(
this.props.children,
child => React.cloneElement(child, { ...this.state })
)
return (
<div ref={this.wrapperRef}>{childrenWithProps}</div>
)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment