'clientHeight' not counting all element - React

862 Views Asked by At

The DOM-tree rendered was

<Grid fluid ={true}>

      <Row>
          <NavigationBar 
           buttonClass='nav-button' 
           className='nav-bar'  
           />
      </Row>

      <section id={sectionList[0]}>
        <Row className='logo-row'>
          <Col className='logo-wrap' xs={3} sm={3} md={2}>
            {Logo}
          </Col>
          <Col xs={9} sm={9} md={10}>
            {ProgrammerName}
          </Col>
        </Row>
        {backgroundImg}
      </section>

 </Grid>

And I was trying to check the clientHeight of the <section> by using following method:

      const height = document.getElementById(sectionList[0]).clientHeight;

However, it seems that this call would only give out the height of the <Row> contained in the <section>, ignoring the {backgroundImg} expression, which itself called to render another <Row> component.

 <Row>
    <FullRowImage src={this.props.src} alt={this.props.alt} />
      <h2>
        <span>
          Some Text
        </span>
      </h2>
  </Row>

What might be the cause of this issue, that clientHeight counts only part of the <section> while leaving out the other?

Thanks.

1

There are 1 best solutions below

0
On

So I finally figured this out. As <FullRowImage /> renders an <img> itself, the clientHeight is called before the <img> is loaded and this would leads to a zero height of <img> as well as <FullRowImage>.

In this case, method componentDidMount() would not be enough since a mounted component does not guarantee a loaded image. On the other hand, onLoad event will come in handy:

class FullRowImage extends React.Component {
   constructor(props){
   super(props);
   this.state = {
     loaded: false,
   };
   this.handleLoaded = this.handleLoaded.bind(this);
 }

handleLoaded(){
   console.log(document.getElementById('test').offsetHeight);
   this.setState(
   {loaded: true,}
   );
 }

 render(){
  return(
    <img id='test'  
     onLoad={this.handleLoaded} 
     src={this.props.src} 
     alt= {this.props.alt} />
    );
  }
}

And this will print the height of <img> after it is loaded.

Thanks to this article Detect when images have finished loading with React