Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Wait for DOM element then react - Reactjs

Hi I have a class component as shown below:

class SomeComponent extends Component {
    componentDidMount = () => {
       const divElement = document.getElementbyId('id'); // this element could take a few seconds to load
       if (props.something1 && props.something2) {
          ..do something with divElement's width
       }
    }
    render() {
      return ....
    }
}

I want to wait until divElement is loaded, or trigger an event when divElement is loaded so I can do my calculation later, tried adding setTimeout which did not work

like image 752
Michael Philips Avatar asked Jun 04 '26 04:06

Michael Philips


1 Answers

Two answers for you:

Use a ref (if your component renders the element)

If the element is rendered by your component, use a ref.

Use a MutationObserver (if the element is outside React)

If the element is completely outside the React part of your page, I'd look for it with getElementById as you are, and if you don't find it, use a MutationObserver to wait for it to be added. Don't forget to remove the mutation observer in componentWillUnmount.

That would look something like this:

componentDidMount = () => {
   const divElement = document.getElementbyId('id');
   if (divElement) {
      this.doStuffWith(divElement);
   } else {
      this.observer = new MutationObserver(() => {
         const divElement = document.getElementbyId('id');
         if (divElement) {
            this.removeObserver();
            this.doStuffWith(divElement);
         }
      });
      this.observer.observe(document, {subtree: true, childList: true});
   }
}
componentWillUnmount = () => {
    this.removeObserver();
}
removeObserver = () => {
    if (this.observer) {
        this.observer.disconnect();
        this.observer = null;
    }
}

(You may have to tweak that, it's off-the-cuff; see the MutationObserver documentation for details.)

like image 77
T.J. Crowder Avatar answered Jun 06 '26 21:06

T.J. Crowder