0

I'm making a portal for a Modal component and when i use the ReactDom.createPortal() function it throws the following error:

Error: Target container is not a DOM element.
createPortal$1 [as createPortal]
D:/UCF/COP4331C/cop4331_largeproject/frontend/node_modules/react-dom/cjs/react-dom.development.js:26195
Modal
D:/UCF/COP4331C/cop4331_largeproject/frontend/src/components/Modal.jsx:21
  18 | 
  19 |     if(!isOpen) return null;
  20 | 
> 21 |     return ReactDom.createPortal(<Background></Background>, portalRoot);
  22 | }
  23 | 
  24 | export default Modal;

This would be my Modal.jsx file:

const portalRoot = document.getElementById("portal-root");

const Modal = ({isOpen, close}) => {

    if(!isOpen) return null;

    return ReactDom.createPortal(<Background></Background>, portalRoot);
}

export default Modal;

and the call in the main html file would be:

<div id="portal-root"></div>

Is there anything that I'm missing to make this work?

  • As of when your `const portalRoot = document.getElementById("portal-root");` statement runs, apparently the element with that `id` isn't in the DOM yet. (E.g., the usual scripts-are-running-before-the-DOM-is-done problem.) But `getElementById` is ***extremely*** fast, you can just put it in your `Modal` component code rather than trying to cache the element reference, which will probably fix the problem by delaying lookup until you use `Modal` (when that element has presumably been put in the DOM). – T.J. Crowder Jul 24 '21 at 11:10
  • yes! changing `getElementById` worked. – python_newbie Jul 24 '21 at 11:18

0 Answers0