reactjsreact-portal

React in-memory Portal


I do want to create a React component tree in memory (not in the DOM) with the same behavior a React Portal has, that is, it should use contexts from the parent component tree.

So is it possible to create something like Portal but instead of render it on a DOM node, "render" it in memory (outside the DOM)?

Note that what I need is the component life-cycle of some components in the tree while the visual part will be hidden, but in my case if I put the component tree in the DOM within a hidden div the performance is not good and then I want to test a different approach.


Solution

  • Two possibilities come to my mind:

    1) create a portal to a DocumentFragment

    When you use ReactDOM.createPortal, you could point it to a documentFragment in memory rather than an element on the page. The nodes that get created should then be appended to that fragment in memory. Whether or not this meets your criteria or not i'm not sure, but it would look something like this:

    class Example extends Component {
      constructor (props) {
        super(props);
        this.fragment = document.createDocumentFragment();
      }
    
      render() {
        return ReactDOM.createPortal(
          this.children,
          this.fragment
        );
    
      }
    }
    

    2) Create a custom reconciler.

    If you want the data to be output in some particular format instead of being DOM nodes, you could create a custom reconciler. This is non-trivial thing to do and uses the react-reconciler package, which the react team describes as "experimental", but it would give you very precise control of what to do with the results of the render.

    If this is something you want to do you can read some at the react-reconciler readme, and it may be useful to look at the configuration files that are used for other reconcilers (see the "host config" links near the bottom of the readme)