Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

106
Vistas
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
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda