0% found this document useful (0 votes)
3 views

React-Create-Portal

The document contains a React component named 'Modal' that renders a modal dialog. It listens for the 'Escape' key to close the modal and uses ReactDOM to create a portal for rendering. The modal is styled with a semi-transparent background and a centered white box for content.

Uploaded by

Sabas Singh
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views

React-Create-Portal

The document contains a React component named 'Modal' that renders a modal dialog. It listens for the 'Escape' key to close the modal and uses ReactDOM to create a portal for rendering. The modal is styled with a semi-transparent background and a centered white box for content.

Uploaded by

Sabas Singh
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 2

// Modal.

js

import React, { useEffect } from "react";

import ReactDOM from "react-dom";

export function Modal({ isOpen, onClose, children }) {

useEffect(() => {

const handleEsc = (e) => {

if (e.key === "Escape") onClose();

};

window.addEventListener("keydown", handleEsc);

return () => window.removeEventListener("keydown", handleEsc);

}, [onClose]);

if (!isOpen) return null;

return ReactDOM.createPortal(

<div

onClick={onClose}

style={{

position: "fixed",

top: 0,

left: 0,

right: 0,

bottom: 0,

backgroundColor: "rgba(0,0,0,0.5)",

zIndex: 9999,

}}

>

<div

onClick={(e) => e.stopPropagation()}

style={{
background: "#fff",

margin: "10% auto",

padding: "20px",

width: "300px",

borderRadius: "8px",

}}

>

{children}

</div>

</div>,

document.getElementById("modal-root")

);

You might also like