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

102
Views
custom hook not returning the dimensions of DOM element through ref parameters

I'm trying to create a custom hook that calculates the width and height of a given DOM element through useRef.

It calculates the dimensions however I'm not seeing any dynamic output. Meaning that as I resize the window, current width and height of the DOM element are not being updated. I need to toggle a css class based on the DOM element's width.

This is my custom hook, which takes a ref as its sole parameter:

  useDimensionObserver = refParam => {

    if (refParam === null) return false;

    const getDimensionsFromRef = refParam => ({ width: refParam.current?.getBoundingClientRect().width, height: refParam.current?.getBoundingClientRect().height }),
      [dimensions, setDimensions] = React.useState(getDimensionsFromRef(refParam));


    React.useEffect(() => {
      const handleResize = () => setDimensions(getDimensionsFromRef(refParam));
      window.addEventListener("resize", handleResize);
      return () => window.removeEventListener("resize", handleResize);
    }, []);

    return refParam ? dimensions : null;

  },

This is the component in which I make use of useDimensionObserver:

 GeneralTotals = (props = IGeneralTotals) => {


    const containerRef = React.useRef(null),
      d = useDimensionObserver(containerRef);

    console.log(d); // As I resize the window, the container is also being resized so d.width and d.height need to be made dynamic.


    //I shall take action with 'd' potentially something like this...
    //if(d !== null && d.width < 450) setToggleInvisibleClass(true)

    return (<div className="card-title-tags" key="cal" ref={containerRef}>
      .....
    </div>);
  };
about 4 years ago · Juan Pablo Isaza
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!