Categories
React Answers

How to Get the Height of an Element with React?

Spread the love

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.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *