react-resize-observer returns null values with Bootstrap modal

400 Views Asked by At

I'm trying to detect a container size change with react-resize-observer. To do so, I have embeded a ResizeObserver in a custom component of mine.

It works great when the component is used in isolation. However, as soon as it is used in a Bootstrap modal (from react-bootstrap), ResizeObserver's onResize callback is called with null values (width === height === 0).

What am I doing wrong?

1

There are 1 best solutions below

0
On

The problem comes from the way the modal is displayed: with an animation. When the modal component is first rendered, it is hidden, thus react-resize-observer reports null values.

Instant fix

Turn the animation off:

<Modal
  animation={false}
>

At least, you should give this a try, just to make sure that fixes the issue.

Make react-resize-observer work while keeping the animation

The trick is to start displaying ResizeObserver and its parent component only when the modal animation has actually started, thanks to the onEntering callback:

export const MyModal = () => {
  const [ showComponent, setShowComponent ] = useState(false);

  return (
    <Modal
      onEntering={() => setShowComponent(true)}
    >
      {showComponent && (
        <div>
          <ResizeObserver onResize={(rect) => {...}}/>
          ...
        </div>
      )}
    </Modal>
  );
}