Get the Height and Width of an Element in React

avatar
Borislav Hadzhiev

Last updated: Jan 16, 2023
6 min

banner

# Table of Contents

  1. Get the Height and Width of an Element in React
  2. Get the Height and Width of an Element using clientWidth and clientHeight
  3. Get the Height and Width of an Element Dynamically in React
  4. Get the Parent height and width in React

# Get the Height and Width of an Element in React

To get the height and width of an Element in React:

  1. Set the ref prop on the element.
  2. In the useLayoutEffect hook, update the state variables for the width and height.
  3. Use the offsetWidth property to get the width of the element.
  4. Use the offsetHeight property to get the width of the element.
App.js
import {useLayoutEffect, useRef, useState} from 'react'; export default function App() { const ref = useRef(null); const [width, setWidth] = useState(0); const [height, setHeight] = useState(0); useLayoutEffect(() => { setWidth(ref.current.offsetWidth); setHeight(ref.current.offsetHeight); }, []); return ( <div ref={ref}> <h2>Width: {width}</h2> <h2>Height: {height}</h2> </div> ); }

react get width and height of element

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.

We passed an empty dependencies array to the useLayoutEffect hook, so it's only going to run when the component mounts.

App.js
useLayoutEffect(() => { setWidth(ref.current.offsetWidth); setHeight(ref.current.offsetHeight); }, []);

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 offsetHeight and offsetWidth properties.

The offsetWidth property returns the width of the element in pixels, including any borders, padding and vertical scrollbars (if present).

The offsetHeight property returns the height of the element in pixels, including vertical padding and borders.

I've also written a tutorial on how to get the window's width and height in React.

# Get the Height and Width of an Element using clientWidth and clientHeight

Alternatively, you can use the clientWidth property, which returns the width of the element in pixels, including padding but excluding borders, margins and vertical scrollbars (if present).

App.js
import {useLayoutEffect, useRef, useState} from 'react'; export default function App() { const ref = useRef(null); const [width, setWidth] = useState(0); const [height, setHeight] = useState(0); useLayoutEffect(() => { setWidth(ref.current.clientWidth); setHeight(ref.current.clientHeight); }, []); return ( <div ref={ref}> <h2>Width: {width}</h2> <h2>Height: {height}</h2> <h2>bobbyhadz.com</h2> </div> ); }

react get width and height of element

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 difference between offsetWidth and clientWidth is that:

  • offsetWidth includes borders, padding and vertical scrollbars (if present).
  • clientWidth includes only padding, but excludes borders, margins and vertical scrollbars (if present).

The difference between offsetHeight and clientHeight is that:

  • offsetHeight includes vertical padding and borders.
  • clientHeight includes padding, but excludes borders, margins and horizontal scrollbars (if present).

# Get the Height and Width of an Element dynamically in React

To get the height and width of an element dynamically:

  1. Add a state variable to the dependencies of the useLayoutEffect hook.
  2. Each time the state changes, update the width and height state variables using the ref.
  3. Add a resize event listener to update the width based on the window size.
App.js
import {useEffect, useLayoutEffect, useRef, useState} from 'react'; export default function App() { const ref = useRef(null); const [numbers, setNumbers] = useState([]); const [width, setWidth] = useState(0); const [height, setHeight] = useState(0); useLayoutEffect(() => { setWidth(ref.current.clientWidth); setHeight(ref.current.clientHeight); }, [numbers]); useEffect(() => { function handleWindowResize() { setWidth(ref.current.clientWidth); setHeight(ref.current.clientHeight); } window.addEventListener('resize', handleWindowResize); return () => { window.removeEventListener('resize', handleWindowResize); }; }, []); return ( <div ref={ref} style={{backgroundColor: 'lightgrey'}}> <h2>Width: {width}</h2> <h2>Height: {height}</h2> {numbers.map((element, index) => { return <h2 key={index}>{element}</h2>; })} <button onClick={() => setNumbers(numbers => [...numbers, Math.random()])} > Increase height </button> </div> ); }

react-get-width-and-height-of-element-dynamically

We initialized a numbers array using the useState() hook.

Notice that we added the numbers array as a dependency to the useLayoutEffect hook.

App.js
useLayoutEffect(() => { setWidth(ref.current.clientWidth); setHeight(ref.current.clientHeight); }, [numbers]);

Every time the contents of the array change, the useLayoutEffect hook runs and updates the width and height state variables.

We used the useEffect hook to add a resize event listener on the window object.

App.js
useEffect(() => { function handleWindowResize() { setWidth(ref.current.clientWidth); setHeight(ref.current.clientHeight); } window.addEventListener('resize', handleWindowResize); return () => { window.removeEventListener('resize', handleWindowResize); }; }, []);

The resize event is fired when the window has been resized.

Every time the window is resized, we update the windowSize state variable according to the new innerWidth and innerHeight of the window.

The function we returned from the useEffect hook will get invoked when the component unmounts.

We used the removeEventListener method to remove the event listener that we previously registered.

The cleanup step is important because we want to make sure we don't have any memory leaks in our application.

# Get the Parent height and width in React

To get the parent height and width in React:

  1. Set the ref prop on the element.
  2. In the useEffect hook, update the state variables for the height and width.
  3. Use the offsetHeight and offsetWidth properties to get the height and width of the element.
App.js
import {useEffect, useRef, useState} from 'react'; export default function App() { const ref = useRef(null); const [height, setHeight] = useState(0); const [width, setWidth] = useState(0); useEffect(() => { setHeight(ref.current.offsetHeight); setWidth(ref.current.offsetWidth); // ๐Ÿ‘‡๏ธ if you need access to parent // of the element on which you set the ref console.log(ref.current.parentElement); console.log(ref.current.parentElement.offsetHeight); console.log(ref.current.parentElement.offsetWidth); }, []); return ( <div ref={ref}> <h2>Width: {width}</h2> <h2>Height: {height}</h2> </div> ); }

react get parent width and height

The useRef() hook can be passed an initial value as an argument.

App.js
const ref = useRef(null);

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.

We passed an empty dependencies array to the useEffect hook, so it's only going to run when the component mounts.

App.js
useEffect(() => { setHeight(ref.current.offsetHeight); setWidth(ref.current.offsetWidth); // ๐Ÿ‘‡๏ธ if you need access to parent // of the element on which you set the ref console.log(ref.current.parentElement); console.log(ref.current.parentElement.offsetHeight); console.log(ref.current.parentElement.offsetWidth); }, []);

We used the useEffect 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 offsetHeight and offsetWidth properties.

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).

If you need to access the width and height of the parent of the element on which you set the ref, use the parentElement property.

App.js
console.log(ref.current.parentElement); console.log(ref.current.parentElement.offsetHeight); console.log(ref.current.parentElement.offsetWidth);

The parentElement property returns the DOM node's parent element or null if the node has no parent, or its parent is not a DOM element.

# Get the Parent height and width using clientHeight and clientWidth

You can alternatively use the clientHeight and clientWidth properties.

App.js
useEffect(() => { setHeight(ref.current.clientHeight); setWidth(ref.current.clientWidth); // ๐Ÿ‘‡๏ธ if you need access to parent // of the element on which you set the ref console.log(ref.current.parentElement); console.log(ref.current.parentElement.clientHeight); console.log(ref.current.parentElement.clientWidth); }, []);

The clientWidth property, which returns the width of the element in pixels, including padding but excluding borders, margins and vertical scrollbars (if present).

The clientHeight property returns the inner height of the element in pixels. It includes padding but excludes borders, margins and horizontal scrollbars (if present).

# Additional Resources

You can learn more about the related topics by checking out the following tutorials:

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.

Copyright ยฉ 2024 Borislav Hadzhiev