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
Two answers for you:
If the element is rendered by your component, use a ref.
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.)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With