Search code examples
reactjsreact-dom

Creating a ReactJS Portal


I am developing a simple modal and some tooltips. I wanted to understand a little about portals so decided to have a go at making one. I have the following code:

            const Portal = React.createClass({
                render() { return null },
                portalElement: null,
                componentDidMount() {
                    let p = this.props.portalId && document.getElementById(this.props.portalId);
                    if(!p) {
                        let p = document.createElement('div');
                        p.id = this.props.portalId;
                        document.body.appendChild(p);
                    }
                    this.portalElement = p;
                    this.componentDidUpdate();
                },
                componentWillUnmount() {
                    document.body.removeChild(this.portalElement);
                },
                componentDidUpdate() {
                    render(<div {...this.props}>{this.props.children}</div>, this.portalElement);
                }
            });

When I run this code, I get the following error in console:

Uncaught Error: _registerComponent(...): Target container is not a DOM element.

My understanding is that it can not find an element where to mount this in body. I have tried adding to index.html but this still hasn't solved it.

Thanks for the help.


Solution

  • Should be var p = ... and not let p = ...