Borislav Hadzhiev
Fri Apr 22 2022·2 min read
Photo by Maria Oliynyk
To get the height of an element using a ref in React:
useEffect()
hook.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); }, []);
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.
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.
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.