Portals

Using ReactDOM.createPortal:

const modalRoot = document.getElementById("modal-root") as HTMLElement;
// assuming in your html file has a div with id 'modal-root';
export class Modal extends React.Component {
el: HTMLElement = document.createElement("div");
componentDidMount() {
modalRoot.appendChild(this.el);
}
componentWillUnmount() {
modalRoot.removeChild(this.el);
}
render() {
return ReactDOM.createPortal(this.props.children, this.el);
}
}

View in the TypeScript Playground

Context of Example

This example is based on the Event Bubbling Through Portal example of React docs.

Last updated on by krishnaUIDev