Portal into a React Component




I ran into this problem when I was working with React Portals.

Normally, when using React Portal, we prepare an HTML root element for the portal to be rendered into. In its example from the React official doc, the app renders into #app-root and the portal element renders into #modal-root:

    <div id="app-root"></div>
    <div id="modal-root"></div>

Note: This is a simplified mind model, the original demo creates another DOM node, and append it into #modal-root.

render() {
  return ReactDOM.createPortal(

Now, what happens if the target element for the portal to render into is not initially rendered in the HTML, but is another React component instead, and it may or may not have been mounted by the time the portal tries to render into it?


In a few words, the approach is that

I have a demo in this CodeSandbox and below is a little illustration:

There is an older but similar implementation of this using class components. It's open sourced as a library React Slots Fill.

Implementation notes

This section is not yet written, some bullet points:


This section is also not yet written, some bullet points:

Relevant links