emre-ozgun
emre-ozgun

Reputation: 762

Is there a way to listen for 'element resize' and NOT for the entire window.resize?

I'm trying to observe the dimensions of a container - a div (its width to be specific) to hide/show certain tags if the available space cannot contain them.

What I'm doing at the moment is to listen for 'window.resize' and make calculations.

Should I be listening just for the container resize instead of the entire window.resize ? If so, how ? Taking into account performance, how could you compare them ?

Current state of my custom hook, as you can see, makes calculations based on window.resize

    import React from "react";
    
    // To decide on whether or not tags should be hidden...
    export const useCalculateAvailableSpace = refParam => {
    
      if (refParam === null) return false;
      const [shouldHide, setShouldHide] = React.useState(false),
        calculateAvailableSpace = refParam => {
    
          if (!refParam || !refParam.current) return;
    
          const containerWidth = refParam.current.getBoundingClientRect().width,
            childrenWidth = Array.from(refParam.current.children).reduce((acc, cur) => acc + cur.getBoundingClientRect().width, 0);
    
          setShouldHide(childrenWidth > containerWidth);
        },
        handleResize = () => {
          calculateAvailableSpace(refParam);
        };
    
      React.useEffect(() => {
        window.addEventListener("resize", handleResize);
        return () => window.removeEventListener("resize", handleResize);
      }, []);
    
      return shouldHide;
    };

Upvotes: 0

Views: 1607

Answers (1)

Diego D
Diego D

Reputation: 8196

https://developer.mozilla.org/en-US/docs/Web/API/Window/resize_event

In some earlier browsers it was possible to register resize event handlers on any HTML element. It is still possible to set onresize attributes or use addEventListener() to set a handler on any element. However, resize events are only fired on the window object (i.e. returned by document.defaultView). Only handlers registered on the window object will receive resize events.

While the resize event fires only for the window nowadays, you can get resize notifications for other elements using the ResizeObserver API.

https://developer.mozilla.org/en-US/docs/Web/API/ResizeObserver

Upvotes: 2

Related Questions