Get the Height of an Element using a Ref in React


Borislav Hadzhiev

Last updated: Apr 22, 2022


Photo from Unsplash

Get the Height of an Element using a Ref in React #

To get the height of an element using a ref in React:

  1. Initialize a state variable that will store the element's height.
  2. Update the element's height in the useEffect() hook.
  3. The height should be set to ref.current.clientHeight.
import {useEffect, useState, useRef} from 'react'; export default function App() { const [divHeight, setDivHeight] = useState(0); const ref = useRef(null); useEffect(() => { setDivHeight(ref.current.clientHeight); console.log('height: ', ref.current.clientHeight); console.log('width: ', ref.current.clientWidth); }, []); return ( <div ref={ref}> <h2>Some</h2> <h2>Content</h2> <h2>{divHeight}</h2> </div> ); }

We get the element's height in the useEffect hook because we need to wait for the ref to be set up and for the div element to be rendered to the DOM before accessing its clientHeight property.

The clientHeight property returns the inner height of an element in pixels. The property includes padding but excludes borders, margins and horizontal scrollbars.

Alternatively, you can use the offsetHeight property, which returns the height of the element in pixels, including vertical padding and borders.

useEffect(() => { setDivHeight(ref.current.offsetHeight); console.log('height: ', ref.current.offsetHeight); console.log('width: ', ref.current.offsetWidth); }, []);
The second parameter we passed to the useEffect hook is an array of dependencies. We only want to set the divHeight state variable after the component mounts, so we used an empty array.

The useRef() hook can be passed an initial value as an argument. The hook returns a mutable ref object whose .current property is initialized to the passed argument.

Notice that we have to access the current property on the ref object to get access to the div element on which we set the ref prop.

When we pass a ref prop to an element, e.g. <div ref={myRef} />, React sets the .current property of the ref object to the corresponding DOM node.

The useRef hook creates a plain JavaScript object, but gives you the same ref object on every render. In other words, it's pretty much a memoized object value with a .current property.

It should be noted that when you change the value of the current property of the ref, no re-renders are caused, so we don't have to add it in the dependencies of useEffect.

The key moment to get the height of an element using a ref is to do it in the useEffect hook, after the ref has been set up and the element has been rendered to the DOM.

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
book cover
You can use the search field on my Home Page to filter through all of my articles.