Using ResizeObserver with React

EDIT: Davidicus's answer below is more complete, look there first

ResizeObserver can't go in the constructor because the div doesn't exist at that point in the component lifecycle.

I don't think you can get around the extra div because react components reduce to html elements anyway.

Put this in componentDidMount and it should work:

componentDidMount() {
   const resizeObserver = new ResizeObserver((entries) => {
        console.log("Hello World");
   });

   resizeObserver.observe(document.getElementById("myDivTag"));
}

ComponentDidMount would be the best place to set up your observer but you also want to disconnect on ComponentWillUnmount.

class MyComponent extends React.Component {
  resizeObserver = null;
  resizeElement = createRef();

  componentDidMount() {
    this.resizeObserver = new ResizeObserver((entries) => {
      // do things
    });

    this.resizeObserver.observe(this.resizeElement.current);
  }

  componentWillUnmount() {
    if (this.resizeObserver) {
      this.resizeObserver.disconnect();
    }
  }

  render() {
    return (
      <div ref={this.resizeElement}>
        ...
      </div>
    );
  }
}