title: Use React Portal to render a child into a DOM node of the parent component
body: <p>What I am attempting to do might seem a little unorthodox so please bear with me. </p>
  
  <p>I want to render a child component into a DOM node of the parent component using a React Portal.</p>
  
  <p>You might think: "This is not the purpose of a Portal and you should just render you children where you want them."</p>
  
  <p>And you may be right but this is a simplified example of an experimental approach I am attempting after trying many other ways.</p>
  
  <p>Anyways, here is the code: <a href="https://codesandbox.io/s/v106r12ln3" rel="noreferrer">(sandbox here)</a></p>
  
  <pre><code>const Child = ({ color }) =&gt; {
    let jsx = &lt;h1&gt;Wow! I am {color}!&lt;/h1&gt;;
    let node = document.getElementById(color);
    return ReactDOM.createPortal(jsx, node);
  };
  
  class Parent extends React.Component {
    state = {
      color: "green"
    };
    changeColor = () =&gt; {
      let color = this.state.color === "green" ? "blue" : "green";
      this.setState({ color });
    };
    render() {
      return (
        &lt;div className="App"&gt;
          &lt;Child color={this.state.color} /&gt;
          &lt;button onClick={this.changeColor}&gt;change color&lt;/button&gt;
          &lt;div className="green" id="green"&gt;
            I render green stuff:
          &lt;/div&gt;
          &lt;div className="blue" id="blue"&gt;
            I render blue stuff:
          &lt;/div&gt;
        &lt;/div&gt;
      );
    };
  };
  </code></pre>
  
  <p>The problem is that the Parent component's "blue" and "green" divs are not yet rendered when the Child tries to render some jsx into them. So I get the error <code>Target container is not a DOM element</code>. The only way I got it to work is have placing those divs into the html file at the root level.</p>
  
  <p>Any advice for how to do what I am trying with Portals? Please don't say to just do this:</p>
  
  <pre><code>&lt;div className="App"&gt;
    &lt;button onClick={this.changeColor}&gt;change color&lt;/button&gt;
    &lt;div className="green" id="green"&gt;
      I render green stuff:
      {this.state.color === 'green' &amp;&amp; &lt;Child color='green' /&gt;}
    &lt;/div&gt;
    &lt;div className="blue" id="blue"&gt;
      I render blue stuff:
      {this.state.color === 'blue' &amp;&amp; &lt;Child color='blue' /&gt;}
    &lt;/div&gt;
  &lt;/div&gt;
  </code></pre>
  
  <p>Thank you in advance :-)</p>