patternjavascriptreactModerate
ReactJS - Get Height of an element
Viewed 0 times
elementheightgetreactjs
Problem
How can I get the Height of an element after React renders that element?
HTML
ReactJS
RESULT
It's calculating the container height before the render (36px). I want to get the height after the render. The right result should be 18px in this case. jsfiddle
HTML
jnknwqkjnkj
jhiwhiw (this is 36px height)
ReactJS
var DivSize = React.createClass({
render: function() {
let elHeight = document.getElementById('container').clientHeight
return Size: {elHeight}px but it should be 18px after the render;
}
});
ReactDOM.render(
,
document.getElementById('container')
);RESULT
Size: 36px but it should be 18px after the renderIt's calculating the container height before the render (36px). I want to get the height after the render. The right result should be 18px in this case. jsfiddle
Solution
See this fiddle (actually updated your's)
You need to hook into
You need to hook into
componentDidMount which is run after render method. There, you get actual height of element.var DivSize = React.createClass({
getInitialState() {
return { state: 0 };
},
componentDidMount() {
const height = document.getElementById('container').clientHeight;
this.setState({ height });
},
render: function() {
return (
Size: {this.state.height}px but it should be 18px after the render
);
}
});
ReactDOM.render(
,
document.getElementById('container')
);
jnknwqkjnkj
jhiwhiw (this is 36px height)
Context
Stack Overflow Q#35153599, score: 38
Revisions (0)
No revisions yet.