May i render the react-portal inside my react application?
Asked Answered
A

1

5

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?

Amphibrach answered 8/11, 2017 at 6:21 Comment(0)
P
6

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,
  );
}
Parrott answered 8/11, 2017 at 7:8 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.