React - Create a modal via React portal

Portals provide a first-class way to render children into a DOM node that exists outside the DOM hierarchy of the parent component. Next, we will show how to create a modal using the React portal.

Modal.js:

import classes from './Modal.module.css'; import ReactDOM from 'react-dom'; const Backdrop = props => { return ( <div className={classes.backdrop} onClick={props.onClose} /> ); }; const ModalOverlay = props => { return ( <div className={classes.modal}> <div className={classes.content}> {props.children} </div> </div> ); }; const portalElement = document.getElementById('overlays'); const Modal = props => { return ( <> {ReactDOM.createPortal(<Backdrop onClose={props.onClose} />, portalElement)} {ReactDOM.createPortal( <ModalOverlay>{props.children}</ModalOverlay>, portalElement )} </> ); }; export default Modal;

Modal.module.css:

.backdrop { position: fixed; top: 0; left: 0; width: 100%; height: 100vh; z-index: 20; background-color: rgba(0, 0, 0, 0.75); } .modal { position: fixed; top: 20vh; left: 5%; width: 90%; background-color: white; padding: 1rem; border-radius: 14px; box-shadow: 0 2px 8px rgba(0, 0, 0, 0.25); z-index: 30; animation: slide-down 300ms ease-out forwards; } @media (min-width: 768px) { .modal { width: 40rem; left: calc(50% - 20rem); } } @keyframes slide-down { from { opacity: 0; transform: translateY(-3rem); } to { opacity: 1; transform: translateY(0); } }

In the following component we will use the modal:

import Modal from './Modal'; ... return ( <Modal onClose={props.onClose}> <h1>My Modal</h1> <button onClick={props.onClose}>Close</button> </Modal> ); ...

Category: React Tag: #react