Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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!

like image 601
WebPansy Avatar asked Jul 15 '16 03:07

WebPansy


1 Answers

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;
like image 194
Mervyn Avatar answered Oct 20 '22 20:10

Mervyn