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

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

  1. You can add lifecycle methods to the class to handle cleanup before a component is unmounted.

    Specifically, you can use the componentWillUnmount() lifecycle hook. As per the docs, "this method is called when a component is being removed from the DOM."

    import ReactDOM from "react-dom";
    
    export default class App extends Component {
      lang = "de-DE";
    
      constructor(props) {
        super(props);
        this.iframeRef = React.createRef();
      }
    
      myMethod = () => {
        const iframeId = this.iframeRef.current.id;
        console.warn(`Component "${iframeId}" will unmount.`);
        console.log(this.iframeRef.current);
      };
    
      componentWillUnmount() {
        this.myMethod();
      }
    
      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
                ref={this.iframeRef}
                id="the_iframe"
                width="95%"
                height="200px"
                scrolling="no"
              ></iframe>
            </div>
          </div>
        );
      }
    }
    
    const getNode = () => document.getElementById("container");
    
    ReactDOM.render(<App />, getNode());
    
    setTimeout(() => {
      ReactDOM.unmountComponentAtNode(getNode());
    }, 1000);
    

    I also included usage of a [Ref] in myMethod to demonstrate accessing the iframe Node. You should see the element logged to the console. This is useful if you need to get properties

    Reply

Leave a Comment