MSK Institute LogoMSK.Institute
HomeCourses
Book Free Demo➔Sign In
Free Demo➔
MSK Institute LogoMSK.Institute

Leading computer training academy in Shikohabad for software engineering, Python, web development, and digital literacy.

ISO 9001:2015 Certified Center
Follow & Connect
4.9

Programs & Admissions

  • All CoursesCatalog
  • Learning PathsRoadmaps
  • Student ProjectsShowcase
  • Live Classes & ScheduleLive
  • Upcoming Batches
  • Campuses & LocationsHub
  • Verify Certificates
  • Book Free Demo Class

Resources & Tools

  • Free Online Mock TestsAll Tests
  • NIELIT CCC Mock TestFree
  • Course & Career FinderQuiz
  • Study Material Hub
  • All MSK ToolsHub
  • Keyboard ShortcutsNew
  • TypeQuest Speed LabTyping
  • MSK Code PlaygroundCode
  • Interactive Tutorials
  • Quick Cheatsheets

Institute & Contact

  • About MSK Institute
  • Careers & InternshipsHiring
  • Publications & Blogs
  • Gali No. 3, Near Gyan Jyoti Public School,
    Adarsh Nagar, Shikohabad, Uttar Pradesh 283135
  • +91 83930 42166
  • mskshikohabad@gmail.com
  • Hours:Mon – Sat: 8:00 AM – 7:00 PM | Sun: 10:00 AM – 2:00 PM
  • 4.9 ★(38 Google Reviews)
© 2026 MSK Institute. All rights reserved.•Privacy Policy•Terms of Service•Disclaimer•Contact Us

Shikohabad's Leading Computer & Coding Academy

Home
Courses
Live
Material
Building Modal Dialogs and Overlays with Portals0%
Study Materials
React.js for IntermediateProgress 0%
1.1Component Reusability and Polymorphic Components1.2Render Props Pattern in Modern React1.3Higher-Order Components vs Modern Hooks1.4Compound Components Pattern Explained
11.1Breaking Out of DOM Hierarchies with createPortal11.2Building Modal Dialogs and Overlays with Portals11.3Event Bubbling Through Portals Explained
HomeTutorialsReact.js for IntermediateBuilding Modal Dialogs and Overlays with Portals
Event Bubbling Through Portals Explained

Building Modal Dialogs and Overlays with Portals

Beginner12 min read•Updated: 2026-11-18•By Er. Sumit Kumar (MSK Institute)
Study MaterialsCheatsheet

1. Anatomy of a Production Modal

A production-grade modal dialog is more than just a centered box. It requires:

  1. 1
    Physical DOM Portaling: Mounting to document.body via createPortal.
  2. 2
    Backdrop / Overlay: Dimming the underlying interface and closing on backdrop click.
  3. 3
    Escape Key Dismissal: Listening for the Escape key to close the modal.
  4. 4
    Body Scroll Locking: Preventing the background page from scrolling while the modal is open.
  5. 5
    Accessibility: Using semantic ARIA attributes (role="dialog", aria-modal="true").
1┌────────────────────────────────────────────────────────┐
2│ Darkened Backdrop Overlay (z-50) │
3│ │
4│ ┌────────────────────────────────────────┐ │
5│ │ Modal Dialog Container │ │
6│ │ │ │
7│ │ Header: Confirm Action [ ✕ ] │ │
8│ │ Body: Are you sure you want to enroll? │ │
9│ │ │ │
10│ │ Footer: [ Cancel ] [ Confirm ] │ │
11│ └────────────────────────────────────────┘ │
12│ │
13└────────────────────────────────────────────────────────┘

2. Complete Modal Implementation

1// src/components/Modal.jsx
2import React, { useEffect } from 'react';
3import { createPortal } from 'react-dom';
4 
5export default function Modal({ isOpen, onClose, title, children }) {
6 // 1. Close on Escape Key & Lock Body Scroll
7 useEffect(() => {
8 if (!isOpen) return;
9 
10 const handleKeyDown = (e) => {
11 if (e.key === 'Escape') {
12 onClose();
13 }
14 };
15 
16 // Lock background page scroll
17 document.body.style.overflow = 'hidden';
18 window.addEventListener('keydown', handleKeyDown);
19 
20 return () => {
21 // Restore scroll and remove listener on cleanup
22 document.body.style.overflow = 'unset';
23 window.removeEventListener('keydown', handleKeyDown);
24 };
25 }, [isOpen, onClose]);
26 
27 // If closed, render nothing
28 if (!isOpen) return null;
29 
30 // 2. Portal to document.body
31 return createPortal(
32 <div
33 className="modal-backdrop"
34 onClick={onClose} // Close when clicking darkened backdrop
35 role="presentation"
36 >
37 <div
38 className="modal-content"
39 role="dialog"
40 aria-modal="true"
41 aria-labelledby="modal-title"
42 onClick={(e) => e.stopPropagation()} // Prevent backdrop click from triggering inside card!
43 >
44 <header className="modal-header">
45 <h3 id="modal-title">{title}</h3>
46 <button
47 type="button"
48 onClick={onClose}
49 className="btn-close"
50 aria-label="Close dialog"
51 >
52 ✕
53 </button>
54 </header>
55 
56 <div className="modal-body">{children}</div>
57 </div>
58 </div>,
59 document.body
60 );
61}

3. Accompanying CSS Styles

1/* Modal Backdrop Overlay */
2.modal-backdrop {
3 position: fixed;
4 inset: 0;
5 background-color: rgba(15, 23, 42, 0.65); /* Darkened blur */
6 backdrop-filter: blur(4px);
7 display: flex;
8 align-items: center;
9 justify-content: center;
10 z-index: 9999;
11 padding: 16px;
12}
13 
14/* Modal Card */
15.modal-content {
16 background-color: #ffffff;
17 border-radius: 16px;
18 width: 100%;
19 max-width: 500px;
20 box-shadow: 0 25px 50px -12px rgba(0, 0, 0, 0.25);
21 animation: modalFadeIn 0.2s cubic-bezier(0.16, 1, 0.3, 1);
22}
23 
24@keyframes modalFadeIn {
25 from { opacity: 0; transform: scale(0.95); }
26 to { opacity: 1; transform: scale(1); }
27}

4. The Critical e.stopPropagation() Nuance

Notice line 35: onClick={(e) => e.stopPropagation()} on .modal-content.

Because the outer .modal-backdrop has an onClick={onClose} handler, clicking anywhere inside the modal card would bubble up to the backdrop and close the modal! Invoking e.stopPropagation() on the inner container halts event bubbling, ensuring the modal only closes when the user clicks outside the card on the darkened backdrop.


Interactive Quiz• Knowledge Check

Practice Quiz

Question 1
Why is e.stopPropagation() called on the inner modal card container?
Question 2
Why should document.body.style.overflow = 'hidden' be set when a modal opens?
Question 3
What must be done in the useEffect cleanup function when locking body scroll?
Question 4
Which standard keyboard key should dismiss accessible modal overlays?
Question 5
What ARIA attributes should be added to an accessible modal dialog?
Next Lesson

Event Bubbling Through Portals Explained

Continue learning with hands-on practice, examples, and exercises in the upcoming topic.

Related Lessons

Previous LessonNext Lesson
Breaking Out of DOM Hierarchies with createPortalEvent Bubbling Through Portals Explained

Practice Quiz

Test your understanding of this lesson with 5 questions. Each question has one correct answer.

Mentor-Led Practical Training

Master React.js for Intermediate with Hands-On Projects

Practice in live mentor-led sessions with real projects, mock tests, and verifiable certification at MSK Institute.

View Full CourseBook Free Demo
PreviousNext
PreviousPrevNext