Reputation: 1731
I'm using Reactjs and I want to get the height of an img element, I want to maintain the ratio of the img so I'm setting the image in css like this.
.img {
position: fixed;
z-index: 999;
width: 30%;
height: auto;
left: 5%;
object-fit: fill;
}
Please noted that the height is "auto" here.
Now I'm simply trying to obtain it's rendered height in componentDidMount() like this:
componentDidMount() {
const height = document.getElementById('ImgID').clientHeight;
const width = document.getElementById('ImgID').clientWidth;
console.log(height, width)
}
The I check simply print the result in console but the log shows that height is 0 and width is 252 (explicit width).
The fact is that the image appeared on the screen and it's height is visually not 0. Then I tried to check attribute 'clientHeight' manually by printing:
console.log(document.getElementById('ImgID').attributes)
By expanding 'style > ownerElement > clientHeight' I see that the client Height is 49, which is not zero, but I just can't get that correct value :/.
I'm looking for a solution to get the height in this situation, it can be done be Javascript/css, or both. I tried to avoid JQuery because React is using virtual DOM, not the browser DOM.
-------------------update--------------------
here's what I got with getBoundingClientRect() suggested by the answer from @ııı
Upvotes: 1
Views: 206
Reputation: 20259
This is actually because the image hasn't loaded yet when componentDidMount()
executes. The <img>
is in the DOM, but the height
is not known until the image loads (unless explicitly set from CSS). Solution is to query the height in onLoad
. See test below:
class Test extends React.Component {
componentDidMount() {
//console.log(this.refs.img.getBoundingClientRect().height);
console.log('componentDidMount', this.refs.img.clientHeight);
}
imageLoaded = () => {
console.log('imageLoaded', this.refs.img.clientHeight);
}
render() {
return <img src="http://placekitten.com/200/200"
ref="img"
onLoad={this.imageLoaded}
/>;
}
}
ReactDOM.render(<Test />, document.getElementById('app'));
<script src="http://unpkg.com/react/umd/react.production.min.js"></script>
<script src="http://unpkg.com/react-dom/umd/react-dom.production.min.js"></script>
<div id="app"></div>
Upvotes: 2