Reference: https://reactjs.org/docs/portals.html
When to use it
Portals provide a first-class way to render children into a DOM node that exists outside the DOM hierarchy of the parent component. Examples of this:
- Modals
- Dialogs and error messages
Creation
In the /public/index.html
file:
<!DOCTYPE html>
<html lang="en">
<head>
<!-- Some code -->
</head>
<body>
<!-- Some code -->
<!-- For Portals -->
<div id="overlays"></div>
<!-- Main React-->
<div id="root"></div>
<!-- Some code -->
</body>
</html>
Use
in the /src/components/UI/Modal.js
file:
import React, { Fragment } from 'react';
import ReactDOM from 'react-dom';
import classes from './Modal.module.css';
const Backdrop = props => {
return <div className={classes.backdrop} onClick={props.myOnClose} />;
};
const ModalOverlay = props => {
return <div className={classes.modal}>
<div>{props.children}</div>
</div>
};
const portalElement = document.getElementById('overlays');
const Modal = props => {
return <Fragment>
{ReactDOM.createPortal(<Backdrop myOnClose={props.myOnClose} />, portalElement)}
{ReactDOM.createPortal(<ModalOverlay>{props.children}</ModalOverlay>, portalElement)}
</Fragment>;
};
export default Modal;