Creating a Modal without using Portals
When creating a modal without portals, a simple component is designed to toggle its visibility using local state management. This method involves rendering the modal content within the component’s DOM hierarchy, potentially causing issues with z-index stacking and CSS containment.
Below is an example that illustrate’s how to creating a modal without using portals.
Javascript
import { useState } from "react" ; import "./App.css" ; const Modal = ({ onClose }) => { return (<div className= "modal" >It's Modal <button onClick={onClose}>Ok</button> </div> ); } function App() { const [showModal, setShowModal] = useState( false ); const onClose = () => setShowModal((prev) => !prev); return ( <div className= "wrapper" > <button onClick={onClose} className= "btn" > Show Modal using portal </button> {showModal && <Modal onClose={onClose} />} </div> ); } export default App; |
CSS
/* App.css */ .wrapper { width : 300px ; padding : 20px ; display : flex; justify- content : center ; flex- direction : column; align-items: center ; height : auto ; overflow : hidden ; gap: 20px ; position : relative ; border : 2px solid black ; } .modal { background-color : green ; width : 200px ; height : 50px ; display : flex; justify- content : space-evenly; align-items: center ; border-radius: 15px ; position : absolute ; left : 50% ; top : 20% ; transform: translate( -50% , -20% ); } .btn { border : 2px solid black ; width : 200px ; height : 50px ; border-radius: 15px ; } |
Output:portals
How to use portals for rendering content outside the parent DOM hierarchy?
Modern web development requires the ability to render content outside of the parent DOM hierarchy. Portals come in handy in such scenarios. They provide a seamless way to render UI elements across different parts of a web application, improving flexibility and performance.
We will discuss about the following usage of portals that render outside the parentDOM hierarchy.
Table of Content
- Creating a Modal without using Portals
- Creating a Modal using Portals