Skip to main content

React Modal

Video Course With Step By Step Explanation Available on Coding Step By STep Android App

coding step by step android app

Scan the above QR or click on this link

React Modal

// App.js
import React, { useState } from "react";
import "./styles.css";
import Modal from "./Modal";

export default function App() {
const [isVisible, setVisible] = useState(false);
return (
<div className="App">
<h1>React Modal</h1>
<button onClick={()=>setVisible(true)}>Show Modal</button>
<Modal
isVisible={isVisible}
title={"New Modal Title"}
content={
<p>
This is modal content. We can write anything that we want to display
in modal body.
</p>
}
footer={<button onClick={() => setVisible(false)}>Cancel</button>}
onClose={() => setVisible(false)}
/>
</div>
);
}

// Modal.js
import { useEffect } from "react";

const Modal = ({ isVisible, title, content, footer, onClose }) => {
const keyDownHandler = ({ key }) => {
switch (key) {
case "Escape":
onClose();
break;
default:
}
};

useEffect(() => {
document.addEventListener("keydown", keyDownHandler);
return () => document.removeEventListener("keydown", keyDownHandler);
});

return isVisible ? (
<div className="modal" onClick={onClose}>
<div className="modal-dialog">
<div className="modal-header">
<h1>{title}</h1>
<span className="modal-close" onClick={onClose}>
&times;
</span>
</div>
<div className="modal-body">
<div className="modal-content">{content}</div>
</div>

{footer && (
<div className="modal-footer">
<p>{footer}</p>
</div>
)}
</div>
</div>
) : (
<></>
);
};

export default Modal;

/* styles.css */
.modal {
position: fixed;
top: 0;
bottom: 0;
left: 0;
right: 0;
width: 100%;
z-index: 9999;
display: flex;
align-items: center;
justify-content: center;
background-color: rgba(0, 0, 0, 0.25);
animation-name: appear;
animation-duration: 300ms;
}

.modal-dialog {
width: 100%;
max-width: 550px;
background: white;
position: relative;
margin: 0 20px;
max-height: calc(100vh - 40px);
text-align: left;
display: flex;
flex-direction: column;
overflow: hidden;
box-shadow: 0 4px 8px 0 rgba(0, 0, 0, 0.2), 0 6px 20px 0 rgba(0, 0, 0, 0.19);
-webkit-animation-name: animatetop;
-webkit-animation-duration: 0.4s;
animation-name: slide-in;
animation-duration: 0.5s;
}

.modal-header,
.modal-footer {
display: flex;
align-items: center;
padding: 1rem;
}

.modal-header {
border-bottom: 1px solid #dbdbdb;
justify-content: space-between;
height: 1vh;
background-color: #3366cc;
color: #fff;
}

.modal-footer {
border-top: 1px solid #dbdbdb;
justify-content: flex-end;
height: 1vh;
background-color: #3366cc;
}

.modal-close {
cursor: pointer;
padding: 1rem;
margin: -1rem -1rem -1rem auto;
font-size: 2rem;
}

.modal-body {
overflow: auto;
}

.modal-content {
padding: 0.5rem;
}