React - Create a modal via React portal
Mihaela Dumitrescu
Posted on June 14, 2021• 5 min read
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 (
);
};
const ModalOverlay = props => {
return (
);
};
const portalElement = document.getElementById('overlays');
const Modal = props => {
return (
<>
{ReactDOM.createPortal( , portalElement)}
{ReactDOM.createPortal(
{props.children} ,
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 (
My Modal
Close
);
...
Please enable JavaScript to view the comments powered by Disqus.