5

I'm using react-portal in my reactjs app. I've created two root elements, one to render the react app into and one for the react-portal:

<html>
    <head></head>
    <body>
        <div id='react-root-element' />
        <div id='react-portal-root-element' />
    </body>
</html>

I also have a component MyComponent which uses react-portal to render content to the react-portal-root-element. The content is wrapped by a div element (let's call it container-div) which has an id.

MyComponent:

export class MyComponent extends React.Component {

    // constructor ... 

    render() {
        return (
            <Portal node={ 'react-portal-root-element' }>
                <div id='divTest_id'>
                    // some more content
                </div>
            </Portal>
        );
    }
}

The parent of MyComponent:

export class MyComponentParent extends React.Component {

    // ... 
    someMethod => {
        this.setState({ myProp: someNewValue });
    }

    render() {
        return (
            <div>
                <MyComponent someProp={ this.state.myProp } />
            </div>
        );
    }
}

When MyComponent renders its content the first time, the div element will be rendered as a child of react-portal-root-element.

Now, if I set a new state in MyComponentParent using setState it will cause a re-render of MyComponent and MyComponent will render the div again. But this time the div of MyComponent is not rendered as a child of react-portal-root-element but as a child of the body element.

I don't understand why this happens. And I was not able to fix this. What I want is that the content of MyComponent is always rendered into the react-portal-root-element.

Can anyone explain this behavior?

Thanks in advance.

MrToast
  • 1,159
  • 13
  • 41

0 Answers0