Reputation: 1162
How can I get the height of a div inside my component? I have the following code:
constructor(...) {
...
this.detailsRef = React.createRef();
}
render() {
return (
<div>
<span>A title</span>
<div ref={this.detailsRef}>Some details</div>
</div>
);
}
I have read that you can get the element's height by doing this:
this.detailsRef.current.clientHeight
or
this.detailsRef.clientHeight
However, that does not work for me. Do anyone have any suggestions?
Answer
Ok, the reason for why I did not get the height from this.detailsRef.current.client
was because my div
with the ref
attached to it was a div created by styled-components
. So when I changed my styled-component div to an ordinary div, it worked.
Upvotes: 1
Views: 8819
Reputation: 4011
Like this:
class Test extends React.Component {
constructor(props) {
super(props);
this.headerRef = React.createRef();
}
componentDidMount() {
console.log(this.headerRef.current.clientHeight);
}
render() {
return (
<div>
<h1 ref={this.headerRef}>Grab this element</h1>
</div>
);
}
}
Upvotes: 3