Skip to content

Commit bca474d

Browse files
committed
Render Modal children on a mounted element
1 parent b82912a commit bca474d

File tree

1 file changed

+13
-2
lines changed

1 file changed

+13
-2
lines changed

content/docs/portals.md

Lines changed: 13 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -65,7 +65,7 @@ This includes event bubbling. An event fired from inside a portal will propagate
6565

6666
A `Parent` component in `#app-root` would be able to catch an uncaught, bubbling event from the sibling node `#modal-root`.
6767

68-
```js{20-23,34-41,45,53-55,62-63,66}
68+
```js{29-34,45-52,56,64-66,73-75,77}
6969
// These two containers are siblings in the DOM
7070
const appRoot = document.getElementById('app-root');
7171
const modalRoot = document.getElementById('modal-root');
@@ -74,10 +74,19 @@ class Modal extends React.Component {
7474
constructor(props) {
7575
super(props);
7676
this.el = document.createElement('div');
77+
// We need to keep track of when the portal element
78+
// is inserted in the DOM tree since we should only
79+
// render the modal's children on a mounted element
80+
this.state = {
81+
mounted: false
82+
};
7783
}
7884
7985
componentDidMount() {
8086
modalRoot.appendChild(this.el);
87+
this.setState({
88+
mounted: true
89+
});
8190
}
8291
8392
componentWillUnmount() {
@@ -86,7 +95,9 @@ class Modal extends React.Component {
8695
8796
render() {
8897
return ReactDOM.createPortal(
89-
this.props.children,
98+
// This will allow any children's 'componentDidMount()'
99+
// to be called on a mounted node
100+
this.state.mounted ? this.props.children : null,
90101
this.el,
91102
);
92103
}

0 commit comments

Comments
 (0)