Regarding React portals, what is the difference between creating a detached node then appending it to the document vs directly having the portal rendered into the document?
In the docs (https://reactjs.org/docs/portals.html) the following is there as an example. On mount, a dynamically created DOM node (this.el) is appended to the portal div. But what's the difference between just appending it directly to the modalRoot element in the document? I don't quite get the commented section of the code.
const modalRoot = document.getElementById('modal-root');
class Modal extends React.Component {
constructor(props) {
super(props);
this.el = document.createElement('div');
}
componentDidMount() {
// The portal element is inserted in the DOM tree after
// the Modal's children are mounted, meaning that children
// will be mounted on a detached DOM node. If a child
// component requires to be attached to the DOM tree
// immediately when mounted, for example to measure a
// DOM node, or uses 'autoFocus' in a descendant, add
// state to Modal and only render the children when Modal
// is inserted in the DOM tree.
modalRoot.appendChild(this.el);
}
componentWillUnmount() {
modalRoot.removeChild(this.el);
}
render() {
return ReactDOM.createPortal(
this.props.children,
this.el
);
}
}