Reputation: 329
I use react 16. I want to render portal inside my app like that:
<html>
<body>
<div id="app-root">
<div>...My app stuff</div>
<div id="modal-root">... portal stuff</div> <-- portal content
</div>
</body>
</html>
But official doc recommends render portal next to, not in app.
<html>
<body>
<div id="app-root"></div>
<div id="modal-root"></div>
</body>
</html>
Is it the only correct way to use the portal?
Upvotes: 5
Views: 1345
Reputation: 281892
The idea of portal is that you can render it anywhere in the DOM tree, all you need is a valid DOM Node to render it into, its not necessary for it to be next to app-root
According to the Docs
However, sometimes it’s useful to insert a child into a different location in the DOM:
render() { // React does *not* create a new div. It renders the children into `domNode`. // domNode is any valid DOM node, regardless of its location in the DOM. return ReactDOM.createPortal( this.props.children, domNode, ); }
Upvotes: 6