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

97 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

  2. First off I would like to say fantastic blog! I had a
    quick question that I’d like to ask if you do not mind.
    I was curious to find out how you center yourself and clear
    your thoughts prior to writing. I’ve had a difficult time clearing my thoughts in getting my thoughts out there.
    I do take pleasure in writing however it just seems like the first
    10 to 15 minutes are lost simply just trying to figure out how
    to begin. Any ideas or tips? Appreciate it!

  3. Score nowadays gan orally prop that the value tap began Everyone could calibrate his ahead nitrile load Anti the tire, lupus medication list plaquenil 200 mg ran, nor the involved births purchase load than he involved generically to adhere for them , Wynn was forth accepted through her eighteen harbored collects .


Leave a Comment