Portals

It's Magic

Portals are a neat way of rendering components into the DOM tree outside of a React tree. You can specify which node you want the parent of the portal to be. So, lets take the simple example below. In the React tree, it goes from A to D. However, clicking the summon magic component button, will render the fourth component after B because its DOM container node is domNodeA (which is where A and B reside); even though in the React tree it resides with C.

Because React and the DOM trees aren't actually the same thing, we can do some cool stuff with Context. We could basically wrap a component in some Context, and then render it using our magic portals in part of the DOM where this Context has no business being.

We can create our magic portal by doing the following:

import ReactDOM from 'react-dom' const Portal = ({ children, domLocation }) => ReactDOM.createPortal(children, domLocation) export default Portal

A

B

C

// Even though D is within the second div, we can render it // within the first div, because we've set the node to the first div in our // useEffect useEffect(() => { setNode(document.getElementById('domNodeA')) }, []) <div id="domNodeA"> <Paragraph>A</Paragraph> <Paragraph>B</Paragraph> </div> <div id="domNodeB"> <Paragraph>C</Paragraph> {summoned && node && ( <Portal domLocation={node}> <Paragraph>D</Paragraph> </Portal> )} </div>