ZeeCoder / use-resize-observer

A React hook that allows you to use a ResizeObserver to measure an element's size.
MIT License
651 stars 42 forks source link

Does not work with flexbox #29

Closed ValentinKaisermayer closed 4 years ago

ValentinKaisermayer commented 4 years ago

Minimal example that uses flex boxes that does not work. Link

ValentinKaisermayer commented 4 years ago

There seems to be something wrong with the variable names. Only

ref, width, height

works.

const App = () => {
  const [open, setOpen] = useState(true);
  const { ref, width, height } = useResizeObserver();
  const { ref2, width2, height2 } = useResizeObserver();
  const { ref3, width3, height3 } = useResizeObserver();

  const renderDiv = () => {
    if (!open) {
      return null;
    }

    return (
      <div
        ref={ref2}
        style={{ flexGrow: "1", backgroundColor: "orange", padding: "1em" }}
      >
        {width2}x{height2}
      </div>
    );
  };

  return (
    <div>
      <button onClick={() => setOpen(!open)}>Toggle</button>
      <div
        style={{
          display: "flex",
          flexDirection: "row",
          alignItems: "stretch"
        }}
      >
        <div
          ref={ref}
          style={{ flexGrow: "1", backgroundColor: "teal", padding: "1em" }}
        >
          {width}x{height}
        </div>
        {renderDiv()}
        <div
          ref={ref3}
          style={{ flexGrow: "1", backgroundColor: "violet", padding: "1em" }}
        >
          {width3}x{height3}
        </div>
      </div>
    </div>
  );
};
ZeeCoder commented 4 years ago

You're using object destructuring wrong, try something like:

const {ref, width: width2, height: height2} = resizeObserver()

Then it should work 👍

ValentinKaisermayer commented 4 years ago

Thanks!