Borislav Hadzhiev
Last updated: Apr 27, 2022
Check out my new book
To get the height of an Element in React:
ref
prop on the element.useLayoutEffect
hook, update the state variable for the height.clientHeight
property to get the height of the element.import {useLayoutEffect, useRef, useState} from 'react'; export default function App() { const ref = useRef(null); const [height, setHeight] = useState(0); const [width, setWidth] = useState(0); useLayoutEffect(() => { setHeight(ref.current.clientHeight); setWidth(ref.current.clientWidth); }, []); return ( <div ref={ref}> <h2>Height: {height}</h2> <h2>Width: {width}</h2> </div> ); }
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.
We passed an empty dependencies array to the useLayoutEffect hook, so it's only going to run when the component mounts.
useLayoutEffect(() => { setHeight(ref.current.clientHeight); setWidth(ref.current.clientWidth); }, []);
The useLayoutEffect
hook is identical to useEffect
, but fires synchronously
after all DOM mutations.
The useLayoutEffect
hook is often used to read layout from the DOM.
We used the useLayoutEffect
hook because we need to wait for the ref
to be
set on the element and for the element to get rendered before accessing its
clientHeight
and clientWidth
properties.
The clientHeight property returns the inner height of the element in pixels. It includes padding but excludes borders, margins and horizontal scrollbars (if present).
The clientWidth property, which returns the width of the element in pixels, including padding but excluding borders, margins and vertical scrollbars (if present).
Alternatively, you can use the offsetHeight property.
useLayoutEffect(() => { setHeight(ref.current.offsetHeight); setWidth(ref.current.offsetWidth); }, []);
The offsetHeight property returns the height of the element in pixels, including vertical padding and borders.
The offsetWidth property returns the width of the element in pixels, including any borders, padding and vertical scrollbars (if present).