javascript - Listen to changes to element's content length or presence of a scrollbar in React - TagMerge
1Listen to changes to element's content length or presence of a scrollbar in ReactListen to changes to element's content length or presence of a scrollbar in React

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

Asked 10 months ago
1
1 answers

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

Source: link

Recent Questions on javascript

    Programming Languages