Skip to content

Commit f3fdc9b

Browse files
committed
Add warning about Modal children mounting detached from DOM tree
1 parent bca474d commit f3fdc9b

File tree

1 file changed

+10
-13
lines changed

1 file changed

+10
-13
lines changed

content/docs/portals.md

Lines changed: 10 additions & 13 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{29-34,45-52,56,64-66,73-75,77}
68+
```js{28-31,42-49,53,61-63,70-71,74}
6969
// These two containers are siblings in the DOM
7070
const appRoot = document.getElementById('app-root');
7171
const modalRoot = document.getElementById('modal-root');
@@ -74,19 +74,18 @@ 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-
};
8377
}
8478
8579
componentDidMount() {
80+
// The portal element is inserted in the DOM tree after
81+
// the Modal's children are mounted, meaning that children
82+
// will be mounted on a detached DOM node. If a child
83+
// component requires to be attached to the DOM tree
84+
// immediately when mounted, for example to measure a
85+
// DOM node, or uses 'autoFocus' in a descendant, add
86+
// state to Modal and only render the children when Modal
87+
// is inserted in the DOM tree.
8688
modalRoot.appendChild(this.el);
87-
this.setState({
88-
mounted: true
89-
});
9089
}
9190
9291
componentWillUnmount() {
@@ -95,9 +94,7 @@ class Modal extends React.Component {
9594
9695
render() {
9796
return ReactDOM.createPortal(
98-
// This will allow any children's 'componentDidMount()'
99-
// to be called on a mounted node
100-
this.state.mounted ? this.props.children : null,
97+
this.props.children,
10198
this.el,
10299
);
103100
}

0 commit comments

Comments
 (0)