6

I'm trying to understand React Portals, so I looked to the documentation.

I still don't understand why in their examples (https://codepen.io/gaearon/pen/yzMaBd and https://reactjs.org/docs/portals.html#event-bubbling-through-portals) they are creating an extra div in the constructor and passing it to the second argument of the createPortal function.

Why don't they use directly the modalRoot container like this ?

const modalRoot = document.getElementById('modal-root');

class Modal extends React.Component {
  render() {
    return ReactDOM.createPortal(
      this.props.children,
      modalRoot,
    );
  }
}

In the codepen example, the explanation is given by this comment

Create a div that we'll render the modal into. Because each Modal component has its own element, we can render multiple modal components into the modal container.

In this stackblitz example, I tried to render multiple components into the portal container without using an extra div and it seems to work perfectly, React.createPortal already appends the child to container, and when the component is unmount, it only removes the child from the container and doesn't clear all the container's content, so we don't have to do this manually. Am I missing something ?

7
  • I don't think there's anything wrong without using <div /> wrapper. Does the docs say so somewhere?
    – Brian Le
    Mar 16, 2019 at 17:18
  • 1
    codepen.io/gaearon/pen/yzMaBd look at the comment in the constructor, they say they are creating a div to be able to render multiple modal components into the modal container. But it's seemed to be already possible without creating an extra div Mar 16, 2019 at 17:22
  • Is that because fragments are not possible in this case? I played with the sandbox and it seemed like so
    – Brian Le
    Mar 16, 2019 at 17:27
  • I don't think it's compulsory though. Been using material-ui and have never seen they put an extra div
    – Brian Le
    Mar 16, 2019 at 17:29
  • 1
    I updated my example stackblitz.com/edit/react-wgnthp?file=PortalComponent.jsx with fragments, it seems to work well. If it's not necessary, I don't understand why they show it in their example because it can generate some problems when a child component requires to be attached to the DOM tree immediately when mounted Mar 16, 2019 at 17:33

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Browse other questions tagged or ask your own question.