0

I have created a simple portal following a tutorial on this site: How to create a React Modal(which is append to `<body>`) with transitions?. The code for the simple portal is:

var Portal = React.createClass({
  render: () => null,
  portalElement: null,
  componentDidMount() {
    var p = this.props.portalId && document.getElementById(this.props.portalId);
    if (!p) {
      var 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() {
    React.render(<div {...this.props}>{this.props.children}</div>, this.portalElement);
  }
});

However rather than rendering the div created above as the parent it renders a div with an undefined id as the parent. I am wondering why this is the case and how I can remove it. Thank you

Community
  • 1
  • 1
Chase James
  • 833
  • 1
  • 7
  • 10
  • Have you checked that `portalId` is in the props of the Portal component? Have you checked that if it exists that it actually has a value? Have you checked that the code is falling into the if block, or does it skip it? Also it'd probably be better just to use a React module for modals, there's at least one good one I know of (just google 'React modal github'). If you're wanting to do it manually for learning purposes then you have to think logically and try to work through it first before posting here being like "It doesn't work, how can I fix it". What have you tried to fix it? – Jayce444 Feb 25 '17 at 13:32

1 Answers1

0

I think you need to pass portalId as a prop to Portal component. Which is undefined right now.

lavish
  • 2,154
  • 1
  • 10
  • 9
  • If it's undefined, it won't go into the if that tries to create the modal – Ruan Mendes Feb 25 '17 at 13:21
  • if `portalId` is undefined this statement will return `undefined` - `this.props.portalId && document.getElementById(this.props.portalId);`. Now that `p` is false it will go in the if statement and will try to create `div`. This is plain coding man. – lavish Feb 25 '17 at 13:26