I’m working in ReactJS. What is the best way to find out when an element has been removed, and does not exist? I prefer to use latest MutationObserverAPI , unless ReactJs has library function to handle this. I can select the Element by Id # attribute.
https://stackoverflow.com/a/61511955/15435022
This is reference code to see when Element does not exist.
function waitForElm(selector) {
return new Promise(resolve => {
if (document.querySelector(selector)) {
return resolve(document.querySelector(selector));
}
const observer = new MutationObserver(mutations => {
if (document.querySelector(selector)) {
observer.disconnect();
resolve(document.querySelector(selector));
}
});
// If you get "parameter 1 is not of type 'Node'" error, see https://stackoverflow.com/a/77855838/492336
observer.observe(document.body, {
childList: true,
subtree: true
});
});
}
2
Answers
Consider this parent/child component
Parent:
Child:
With this setup, the function "callback" would only fire once the child component is unmounted and removed from the dom. Note that the useEffect cleanup function fires any time a dependency changes in the dependency array, as well as if the component unmounts. For your case, if you have a useEffect with no dependencies, it should serve your needs!
The MutationObserverApi works as well! My personal preference is to leverage useEffect, and if you have a specific component you’re expecting to be removed from the dom, it’s easier (at least in my mind) to have the code handling seeing if it unmounts/performing some action within the component itself!
You may use a ref Callback.
As you know, React will call this function with the DOM node when it’s time to set the ref, and with null when it’s time to clear it. For more about it, please see here How to manage a list of refs using a ref callback
The following sample code demonstrates the same.
As you know, while toggling the state by the code, the element will be added and removed from DOM.
App.js
Test run – Console logs generated on loading and clicking the button