Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

96
Views
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?

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

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

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!