ReactJS - Get Height of an element
For those who are interested in using react hooks
, this might help you get started.
import React, { useState, useEffect, useRef } from 'react'
export default () => {
const [height, setHeight] = useState(0)
const ref = useRef(null)
useEffect(() => {
setHeight(ref.current.clientHeight)
})
return (
<div ref={ref}>
{height}
</div>
)
}
Following is an up to date ES6 example using a ref.
Remember that we have to use a React class component since we need to access the Lifecycle method componentDidMount()
because we can only determine the height of an element after it is rendered in the DOM.
import React, {Component} from 'react'
import {render} from 'react-dom'
class DivSize extends Component {
constructor(props) {
super(props)
this.state = {
height: 0
}
}
componentDidMount() {
const height = this.divElement.clientHeight;
this.setState({ height });
}
render() {
return (
<div
className="test"
ref={ (divElement) => { this.divElement = divElement } }
>
Size: <b>{this.state.height}px</b> but it should be 18px after the render
</div>
)
}
}
render(<DivSize />, document.querySelector('#container'))
You can find the running example here: https://codepen.io/bassgang/pen/povzjKw
See this fiddle (actually updated your's)
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 (
<div className="test">
Size: <b>{this.state.height}px</b> but it should be 18px after the render
</div>
);
}
});
ReactDOM.render(
<DivSize />,
document.getElementById('container')
);
<script src="https://facebook.github.io/react/js/jsfiddle-integration-babel.js"></script>
<div id="container">
<p>
jnknwqkjnkj<br>
jhiwhiw (this is 36px height)
</p>
<!-- This element's contents will be replaced with your component. -->
</div>