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:


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 className="App-link">

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

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

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

  1. 635805 722076Id need to talk to you here. Which isnt something Which i do! I really like to reading a post that need to get individuals to think. Also, thank you for allowing me to comment! 965909


Leave a Comment