Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to correct React Portal error: Target container is not a DOM element

im having an issue getting react portals working. I dont understand why I am receiving error message portal id is not DOM element that is clearly a valid DOM element.

I have a sandbox here

Code in its entirety presented here. The console.log reports correctly that the element is a DOM element but React is throwing an error.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

import "./styles.css";
import { createPortal } from "react-dom";
import { useEffect, useState } from "react";

export default function App() {
  const [portalDiv, setPortalDiv] = useState(undefined);

  useEffect(() => {
    let pd = document.getElementById("portalDiv");
    console.log(pd);
    setPortalDiv(pd);
  }, []);

  return (
    <>
      <div id="portalDiv">portal container</div>
      <div className="app">
        {/* {console.log("render portaldiv", portalDiv)} */}
        {
          (portalDiv &&
            createPortal(
              <>
                <h1>Inside portal</h1>
              </>
            ),
          portalDiv)
        }
        <h1>Outside portal</h1>
      </div>
    </>
  );
}

Any advice appreciated. Thanks.

>Solution :

This usecase is not recommended as stated in my comment, but here is a reproducible example.

If you intend to inject a React Node into VDOM, you should use React API for that, so you won’t get a race condition while querying the DOM via DOM API.

import "./styles.css";
import { createPortal } from "react-dom";
import { useRef } from "react";

export default function App() {
  const containerRef = useRef();

  return (
    <>
      <div ref={containerRef}>portal container</div>
      <div id="app">
        {containerRef.current &&
          createPortal(<h1>Example Element</h1>, containerRef.current)}
        <h1>Outside portal</h1>
      </div>
    </>
  );
}

Edit portal id is not a DOM element (forked)

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading