Sometimes, we want to get the height of an element with React.
In this article, we’ll look at how to get the height of an element with React.
Get the Height of an Element with React
To get the height of an element with React, we can assign a ref to the element we want to get the height for.
Then we can use the clientHeight
property to get the height.
For instance, we write:
import React, { useRef } from "react";
export default function App() {
const elementRef = useRef(null);
console.log(elementRef.current?.clientHeight);
return <div ref={elementRef}>hello world</div>;
}
We call the useRef
hook and assign the returned ref to elementRef
.
Then we set elementRef
as the value of the ref
prop of the div.
Finally, we log the height of the div by logging elementRef.current?.clientHeight
.
Therefore, we should see 18 logged, which is the height of the div in pixels.
Conclusion
To get the height of an element with React, we can assign a ref to the element we want to get the height for.
Then we can use the clientHeight
property to get the height.