Failed to execute 'removeChild' on 'Node': The node to be removed is not a child of this node. Removing React portal target

33 views Asked by At

The code attached bellow throw an error. It looks like react thing with fragment but i removed all of them. I also tried remove and removeChild.

The idea was to add a click on the body and remove all notification and insure only one is in the dom

Any ideas how to resolve this or its a bug ?




import React, { useEffect, useRef, useId } from "react";
import ReactDOM from "react-dom";


const Modal = (props) => {
  useEffect(() => {
    const clearNotifications = () => {
      var container = document.getElementById("notifications");

    
        if (container) {
          while (container.firstChild) {
            container.firstChild.remove();
          }
        }
      
    };

    const body = document.getElementById("boom-trach"); ///body

    body.addEventListener("click", clearNotifications, true);

    return () => {
      console.log("removed", body);
      body.removeEventListener("click", clearNotifications, true);
    };
  }, []);

  const SetBody = () => {
    return <div id="modal">sss</div>;
  };

  return ReactDOM.createPortal(
    <SetBody />,
    document.getElementById("notifications")
  );
};

export default Modal;

this is the react code that cause container.removeChild

  if (container.nodeType === COMMENT_NODE) {
    container.parentNode.removeChild(child);
  } else {
    container.removeChild(child);
  }
}```
1

There are 1 answers

0
Pohakoo On

Might be easier to debug if you send a copy of the error, but:

const body = document.getElementById("boom-trach"); ///body
body.addEventListener("click", clearNotifications, true);

Put this code in a useEffect hook, document.getElementById doesn't work unless it's in one. Also:

if (container) {
  if (container) {
    while (container.firstChild) {
      container.firstChild.remove();
    }
  }
}

Remove one of the if statements, the inner one will always be true if the outer one is true