As you can see from the sandbox, she created two functional components to provide the modal with dynamic content. The <ModalProvider /> component contains a DOM element with a ref attached ( <div ref={modalRef}/> ), and a context Provider that wraps the entire application and distributes the ref’s current value to any relevant Consumers within it. The second component is the modal itself. Whenever a <Modal/> component is rendered it will attempt to retrieve the modalRef element through useContext() . If a ref exists, instead of the component mounting in its expected position in the DOM tree it will instead create a React Portal and inject the modal’s children into the ref element. 💥

The Modal component can now be used anywhere within the ModalProvider to render dynamic content on top of the application. One small caveat to this approach is the body will continue to scroll on iOS whenever the modal is mounted. I highly recommend checking out Will Po’s article on Body scroll lock for some solutions.

Like the article? Follow me on Twitter