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

175
Views
Getting dynamic width of div after rendering

I want to get the width of a dynamic div after it's painted, but I can't tell how. This is what I am doing :

const ref=useRef();
useEffect(()=>{
console.log('REF',ref.current.offSetWidth)
},[])



return (
<div ref={ref}>


</div>

I tried window.resize eventListener, but it only gets triggered if the screen dimensions changed. My question is there anyway to get the width of a div after it renders on the screen ? I'm not setting the width beforehand, it's just taking 100% of parent element inside a flex box

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

0

You can use the ResizeObserver, a simple implementation with React could be something like this:

import {useRef, useEffect} from 'react'

export default function App() {
  const divRef = useRef()

  useEffect(() => {
    new ResizeObserver(() => {
      console.log('Width: ', divRef.current.clientWidth)
    }).observe(divRef.current)
  }, [])

  return (
    <div ref={divRef}>
    </div>
  );
}
about 4 years ago · Juan Pablo Isaza Report

0

Your code is working I think. Here is a short Typescript implementation to show my point:

...

const ref = useRef<HTMLDivElement>();
    return (
        <div ref={ref as MutableRefObject<HTMLDivElement>}>
            <button onClick={() => console.log('REF', ref?.current?.clientWidth)}>TEST</button>
        </div>
    );

...

Console result on button click before resizing: [![enter image description here][1]][1]

Console result on button click after resizing: [![enter image description here][2]][2]

I guess the reason you never see the changes is that you have a use effect here that only runs once. Also note that changes in the ref object will not automatically trigger a re-render. [1]: https://i.stack.imgur.com/uCmz4.png [2]: https://i.stack.imgur.com/cWpVM.png

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!