Created
August 24, 2018 11:50
-
-
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
This file contains hidden or 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
// 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