'Listen to changes to element's content length or presence of a scrollbar in React

I have a container with overflow-y: auto and I need to shift the rest of my layout depending on whether its scrollbar is present or not.

I know I can check for scrollbar's presence at any given time:

const scrollbarVisible = (e) => e.scrollHeight > e.clientHeight

But I don't know how to listen/observe for the scrollbar's presence in order to trigger a re-render of my side-dock.

What are my options? Do I have any besides checking for the scrollbar in regular intervals with setInterval to detect the change that way?



Solution 1:[1]

You could use the resize observer api to check for size changes in an element. An example of usage, also present in the link I mentioned, follows:

import * as React from 'react'
import useResizeObserver from '@react-hook/resize-observer'

const useSize = (target) => {
  const [size, setSize] = React.useState()

  React.useLayoutEffect(() => {
    setSize(target.current.getBoundingClientRect())
  }, [target])

  // Where the magic happens
  useResizeObserver(target, (entry) => setSize(entry.contentRect))
  return size
}

const App = () => {
  const target = React.useRef(null)
  const size = useSize(target)
  return (
    <pre ref={target}>
      {JSON.stringify({width: size.width, height: size.height}, null, 2)}
    </pre>
  )
}

After that you can check for the overflow as you did with JS

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 prieston