Ajay Gaur Ajay Gaur - 3 years ago 80
Javascript Question

How can I render a component in DOM body even if some other component renders it in react?

I have a component, say

X
which is rendered by my
app
and in the DOM-body. I have another component
Y
which is rendered by the component
X
but the component
Y
should be opened in full-screen. So, I need to render this in
document.body
rather inside component
X
even if
X
renders it.

React Components' structure is:

app
-X
-Y (in Full Screen)


the structure now should look like:

<body>
<div class="X">
<div class="Y">
</div>
</div>
</body>


and the rendered flow should be :

app.body
-X
-Y


and the DOM structure should be:

<body>
<div class="X">
</div>
<div class="Y">
</div>
</body>


How can I do this. Also, I am using ES6 classes for making react-components.

Answer Source

UPDATE: Starting from React 16, there is official support for portals.

Portals provide a first-class way to render children into a DOM node that exists outside the DOM hierarchy of the parent component.


I wouldn't recommend to use this solution as it is using an undocumented React API. Disclaimer provided, here it is:

class Portal extends React.Component {
  componentDidUpdate() {
    this._renderLayer();
  }
  
  componentDidMount() {
    this._renderLayer();
  }
  
  componentWillUnmount() {
    ReactDOM.unmountComponentAtNode(document.getElementById(this.props.container));
  }

  _renderLayer() {
    ReactDOM.unstable_renderSubtreeIntoContainer(this, this.props.children, document.getElementById(this.props.container));
  }
  render() {
    return null;
  }
}

class Y extends React.Component {
  render() {
    return <div>Y</div>;
  }
}

class X extends React.Component {
  render() {
    return (
      <div> 
        X
        <Portal container="Y">
          <Y />
        </Portal>
      </div>
    );
  }
}

ReactDOM.render(<X/>, document.getElementById('X'));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>

<div id='X'></div>
<div id='Y'></div>

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download