I need to get the dimensions of an image with React. I found a library called react-measure that computes measurements of React components. It works, but I can't get it to fire when the image has loaded. I need to get it to fire when the image loads so I get accurate dimensions and not 0 x 157 or something like that.
I tried using the onLoad
Image Event to detect when the image has loaded, but I didn't get satisfactory results. Essentially what I've done is when the image has loaded (handleImageLoaded()
has been called), change the hasLoaded
state property to true
. I know for a fact that hasLoaded
has been changed to true
because it says so: Image Loaded: true
.
What I noticed is that I can calculate the dimensions for only images that have been cached...
Here is a demo video: cl.ly/250M2g3X1k21
Is there a better, more concise way of retrieving dimensions properly with React?
Here is the code:
import React, {Component} from 'react';
import Measure from '../src/react-measure';
class AtomicImage extends Component {
constructor() {
super();
this.state = {
hasLoaded: false,
dimensions: {}
};
this.onMeasure = this.onMeasure.bind(this);
this.handleImageLoaded = this.handleImageLoaded.bind(this);
}
onMeasure(dimensions) {
this.setState({dimensions});
}
handleImageLoaded() {
this.setState({hasLoaded: true});
}
render() {
const {src} = this.props;
const {hasLoaded, dimensions} = this.state;
const {width, height} = dimensions;
return(
<div>
<p>Dimensions: {width} x {height}</p>
<p>Image Loaded: {hasLoaded ? 'true' : 'false'}</p>
<Measure onMeasure={this.onMeasure} shouldMeasure={hasLoaded === true}>
<div style={{display: 'inline-block'}}>
<img src={src} onLoad={this.handleImageLoaded}/>
</div>
</Measure>
</div>
);
}
}
export default AtomicImage;
Here is the parent code. It's not really important—just passes src
to the AtomicImage
element:
import React, {Component} from 'react';
import ReactDOM from 'react-dom';
import AtomicImage from './AtomicImage';
class App extends Component {
constructor() {
super();
this.state = {src: ''}
this.handleOnChange = this.handleOnChange.bind(this);
}
handleOnChange(e) {
this.setState({src: e.target.value});
}
render() {
const {src} = this.state;
return (
<div>
<div>
<input onChange={this.handleOnChange} type=text/>
</div>
<AtomicImage src={src} />
</div>
)
}
}
ReactDOM.render(<App />, document.getElementById('app'));