Resize observer in React

Posted by everrover on March 11, 2023

#js
#observers
#react
#reacthooks
#webdevelopment

ResizeObserver monitors the changes in size and position of an observed DOM element. It is a very less often used API. But it has it’s moments. Again it’s an async non-blocking API.

Here is how it’s defined.

jsx
const observer = new ResizeObserver((entries, observer) => {
		// callback function
    entries.forEach((entry, idx) => {
	    console.log(entry)
			// do something with entry
	  })
})

The entry object has with it the box-sizes of the target element under observation(as shown in image) and the target element itself.

Resize observer entry object

I think the most often used property is contentRect and target property. Here is an example of contentRect object...

json
{
	bottom: 500,
	height: 484,
	left: 0,
	right: 1869,
	top: 16,
	width: 1869,
	x: 0,
	y: 16
}

Though devicePixelContentBoxSize, borderBoxSize and contentBoxSize are present for certain use cases as well. All have same contents as shown,

{inlineSize: 1869, blockSize: 484} 

There are three basic methods on observer. Functionality of these three methods are same as that of IntersectionObserver. These are

  • .observe()
  • .unobserve()
  • .disconnect()

The practical use cases include styling elements on basis of position and box dimensions, multi-image banners and holding scroll position on window resize. Here is the code of my demo for it.

Sources