reactjsrenderrootmicro-frontendunmount

How remove or unmount React App from a website properly


In my website, i have a button to launch an react app in a specific div. When i click upon it, i create a react root div and render the react app inside. What is the proper way to close it?

   <!--HTML from the website -->
  <body>
    <button id="btn">Launch React App</button>
    
    <script type="module" src="/src/main.tsx"></script>
  </body>
//main.js from the react App
import React from "react";
import ReactDOM from "react-dom/client";
import "./global.scss";
import App from "./App";

const btn = document.getElementById("btn");

btn.onclick = () => {
  const root_div = document.createElement("div");
  root_div.id    = "root";
  document.body.appendChild(root_div);

  const root = ReactDOM.createRoot(root_div);

  root.render(
    <React.StrictMode>
      <App />
    </React.StrictMode>
  );
};

Solution

  • Finally I did this for React v18:

      <!--HTML from the website -->
      <body>
        <button id="btn">Launch React App</button>
        
        <script type="module" src="/src/main.tsx"></script>
      </body>
    
    //main.js
    /*Librairies*/
    import React from 'react';
    import ReactDOM from 'react-dom/client'; //React 18
    /*Components*/
    import App from './App';
    import CloseApp from './components/CloseApp/CloseApp';
    /*CSS*/
    import './global.scss';
    
    const btn = document.getElementById('btn');
    
    /*CREATE ROOT ELEMENT & RENDER IT with React 18*/
    btn.onclick = () => {
    
      const div_root = document.createElement('div');
      div_root.id    = 'div_root';
    
      const root = ReactDOM.createRoot(div_root);
      document.body.appendChild(div_root);
    
      root.render(
        <React.StrictMode>
          <App />
          <CloseApp root={root} />
        </React.StrictMode>
      );
    };
    
    //CloseApp.js
    import ReactDOM from 'react-dom/client'; //React 18
    export default function CloseApp({ root }) {
      const close = () => {
        const div_root = document.getElementById('div_root');
        root.unmount(); //React 18
        div_root.remove();
      };
    
      return (
        <button onClick={close}>CLOSE</button>
      );
    }