How to know the height other component in a div

(Gervwyk) #1

I have a component which renders two child component, and the second child component needs to know the hight of the first child component to render effectively. What would be the best strategy to achieve this?

Here is a simple code example:

class Parent extends React.Component {
   render () {
       return (
             <div style={{height: '300px'}}>
                  <ChildOne />
                  <ChildTwo />

Lets say that ChildOne is a table with dynamic hight and ChildTwo is a svg for which I have to pass the exact height which is needed to fill the div after the dynamic table is rendered. What would be the best strategy to achieve this? Any examples?

(Akmurat Saktagan) #2

I think you need a new state property for height and callback function

onHeightChange(newHeight) {
    height: newHeight


<ChildOne onHeightChange={onHeightChange.bind(this)} />
<ChildTwo height={this.state.height} />

Callback function should return a new height response to window resize or whatever…

(Jakob Lind) #3

To be able to get the height you need to access the DOM. The way you do that with react is with the ref-tag

It would look something like this inside your ChildOne component

<div ref={(elem) => this.elemHeight = elem.clientHeight}/>

You would be able to access the height with this.elemHeight .

(Gervwyk) #4

Thanks @jakoblind . thats a great solution. It’s much cleaner than handling the state changes. I I just have to test it, I think I’ll just have to make sure the component rerenders on size change.

(Jakob Lind) #5

Yes, you need to put the height into the state of the parent component so that the child components gets rerendered on height change.