Sometimes, we want to get a rendered component height with React.
In this article, we’ll look at how to get a rendered component height with React.
How to get a rendered component height with React?
To get a rendered component height with React, we can use the element’s clientHeight
property.
For instance, we write:
import React, { useEffect, useRef } from "react";
export default function App() {
const ref = useRef();
useEffect(() => {
console.log(ref.current?.clientHeight);
}, []);
return <div ref={ref}>hello world</div>;
}
We assign the ref
ref to the ref
prop of the div.
Then we call useEffect
with a callback and an empty array to get the element’s height when the component mounts.
In the useEffect
callback, we use ref.current?.clientHeight
to get the div’s height in pixels.
Conclusion
To get a rendered component height with React, we can use the element’s clientHeight
property.