DEV Community

Tim Perry
Tim Perry

Posted on

React Reverse Portals

Hey Dev.to!

I've just built a new library for React: https://github.com/httptoolkit/react-reverse-portal

It lets you define, mount & render a component once, in one place, and then place it in the React & DOM tree somewhere totally different, move it up/down/around the tree later, or even pull it out of the page entirely and put it back, all without remounting or necessarily rerendering.

It's similar to the built-in React portals (and it uses them internally), but effectively the opposite. Instead of defining some content within your tree and pushing it elsewhere via raw DOM, you define your content elsewhere and then pull it into the React tree where you want it to appear.

No DOM work required: just get a node, place an InPortal somewhere with your content & the node, and an OutPortal elsewhere with the node, and your content is magically sent from one to the other.

Useful if you want to avoid unnecessary recreation of components. That lets you avoid losing react state or DOM state (e.g. playing video elements), avoid recreating expensive-to-initialize components, and generally separate here your component is define from where it's used.

There's an example in the readme and a storybook of live examples too.

Let me know what you think!

Top comments (1)

Collapse
 
anand2489 profile image
Anand Gupta

@pimterry Can we use your library react-reverse-portal in production level code or there are some limitations which you know/want to highlight ?

I have following queries around it though

  1. New parent would be able to completely control InPortal component via props & refs
  2. InPortal component would get new props in current render cycle of the parent without any delay
  3. Any case/scenario where react-reverse-portal won't work :)