WebPansy
WebPansy

Reputation: 63

Why can't I get the DOMNode's style (scrollHeight) in the React componentDidMount?

I am developping a React Application and trying to get the computed style 'scrollHeight' of a DOM Element.

I put this code in the componentDidMount:

componentDidMount() {

        // let _this = this;
        // window.onload = function(){


        let imgFigureDOM = findDOMNode(_this.refs.imgFigure0),
            imgW = imgFigureDOM.scrollWidth,
            imgH = imgFigureDOM.scrollHeight;
        // }
   }

But, I can't get the correct value of scrollHeight only in the chrome browser.It seems that the chrome is not enough fast to render the DOMNode completely when the findDOMNode execute.

The value is correct when I use window.onload as above, but Shouldn't the DOMNode was completely loaded when the componentDidMount execute?

Thank you for your patient answer!

Upvotes: 6

Views: 6008

Answers (1)

Mervyn
Mervyn

Reputation: 583

componentDidMount() is called when your React component is rendered. React has rendered an <img> tag, that doesn't mean that the image is loaded.

Let's set up some basic definitions to distinguish rendered from loaded:

  • rendered: React has converted your virtual DOM elements (specified in the render method) into real DOM elements and attached them to the DOM.

  • loaded: Image data or other remote content has downloaded completely (or failed to download).

So just add the onLoad and onError event handlers to your React <img> tag and away you go. image-events

Short Example:

import React from 'react';

class ImageWithStatusText extends React.Component {
  constructor(props) {
  super(props);
  this.state = { imageStatus: null };
}

handleImageLoaded(e){
  this.setState({ imageStatus: 'loaded' });
  console.log(e.target.scrollHeight);
}

handleImageErrored() {
  this.setState({ imageStatus: 'failed to load' });
}

render() {
  return (
    <div>
      <img
        src={this.props.imageUrl}
        onLoad={this.handleImageLoaded.bind(this)}
        onError={this.handleImageErrored.bind(this)}
      />
      {this.state.imageStatus}
    </div>
  );
 }
}
export default ImageWithStatusText;

Upvotes: 4

Related Questions