How to call a method when a DOM element is destroyed in React

I’m new to React. I have an <iframe>. Before it is destroyed or removed I want to call some clean-up code. But I’m not sure how to call that method before destroy. Here is my code:

App.js

import React, { Component } from "react";

import "./App.css";

export default class App extends Component {
  lang = "de-DE";

  myMethod =()=> {
    var in_dom = document.body.contains("the_iframe");
    var observer = new MutationObserver(function(mutations) {
    if (document.body.contains("the_iframe")) {
      if (!in_dom) {
        console.log("element inserted");
      }
      in_dom = true;
      } else if (in_dom) {
       in_dom = false;
       console.log("element removed");
      }

    });
    observer.observe(document.body, {childList: true, subtree: true});
  }

  render() {
    ...
    return (
      <div className="App">
        <header className="App-header">
          <span className="App-link">
            Change Language
          </span>
          <span className="App-link">
            Logout
          </span>
        </header>
        <div>
          <iframe
            id="the_iframe"
            width="95%"
            height="200px"
            scrolling="no"
            beforeunload="myMethod()"
          ></iframe>
        </div>
      </div>
    );
  }
}

I took help from here:
DOM event when element is removed

Some information I took from here also:
DOMContentLoaded, load, beforeunload, unload

4 thoughts on “How to call a method when a DOM element is destroyed in React”

Leave a Comment