Portals provide a first-class way to render children into a DOM node that exists outside the DOM hierarchy of the parent component.
index.html
<div>
<div id="root"></div>
<div id="modal"></div>
</div>
Modal.js
const Modal = ({ children }) => {
return ReactDOM.createPortal(children, document.getElementById('modal'));
};
AboutPage.js
class AboutPage extends Component {
state = { modalOpened: true };
toggleModal = () =>
this.setState({
modalOpened: !this.state.modalOpened
});
render() {
const { modalOpened } = this.state;
return (
<div>
<h1>About Us</h1>
<button onClick={this.toggleModal}>toggle modal</button>
{modalOpened && <Modal>Content inside of modal</Modal>}
</div>
);
}
}