Unable to set the width of container dynamically in react typescript

1k Views Asked by At

I am trying to get the width of a container div as the screen resizes and set the width in a react typescript project. I'm using the ResizeObserver from @juggle/resize-observer to track the width. And created an instance resizeObserver inside the component and use it to observe the container width

const Component = () => {
    const containerRef = useRef<HTMLDivElement>(null)
    const [width, setWidth] = useState(600)

    const resizeObserver = new ResizeObserver((entries, observer) => {
        if (!Array.isArray(entries)) return
        if (!entries.length) return
        const entry = entries[0]
        setWidth(entry.contentRect.width)
        observer.disconnect()
})

useEffect(() => {
    // not providing the dependency array!?
    if(svgContainerRef.current) {
      resizeObserver.observe(svgContainerRef.current)
    }
})

return (
    <div className="w-full h-fit" ref={containerRef}>
       <svg width={width} height={height}>
       ...
       </svg>
    </div>
)

I'm trying to find a working/efficient way to set the width of container div whenever the screen is resized so that the width of the child svg elements is dynamically set. Any help/suggestions would be really helpful.

1

There are 1 best solutions below

0
On

You should disconnect in the teardown logic of useEffect, not inside the observer callback. So something like this:

const Component = () => {
  const containerRef = useRef<HTMLDivElement>(null)
  const [width, setWidth] = useState(600)


  useEffect(() => {
    const resizeObserver = new ResizeObserver((entries) => {
        if (!Array.isArray(entries)) return
        if (!entries.length) return
        const entry = entries[0]
        setWidth(entry.contentRect.width)
    })
    // assert svgContainerRef.current !== null
    const elem = svgContainerRef.current
    resizeObserver.observe(elem)
    return () => resizeObserver.unobserve(elem)
  }, [])

  return (
    <div className="w-full h-fit" ref={containerRef}>
       <svg width={width} height={height}>
       ...
       </svg>
    </div>
  )