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.
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>
Simply render each of your component in their own <div>
:
<body>
<div id="app"></div>
<div id="Y"></div>
</body>
And render each component separately:
React.render(ComponentApp, document.getElementById("app"));
React.render(ComponentX, document.getElementById("X"));
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.