we want to open a modal then open another one inside the first one and close the higher modal with click in outside of the modal.
first we make a component for modal:
import React from "react";
function Modal(props) {
const divStyle = {
display: props.displayModal ? "block" : "none",
};
function closeModal(e) {
e.stopPropagation();
props.closeModal();
}
return (
<div className="modal" onClick={closeModal} style={divStyle}>
<div className="modal-content" onClick={(e) => e.stopPropagation()}>
<span className="close" onClick={closeModal}>
×
</span>
{props.children}
</div>
</div>
);
}
export default Modal;
then we use this component where we need it
import React, { useState } from "react";
import "./App.css";
import Modal from "./Modal";
function App() {
const [modal, setModal] = useState(false);
const [modal1, setModal1] = useState(false);
const selectModal = (info = "") => {
setModal((perv) => !perv);
};
return (
<div className="App">
<p onClick={() => selectModal("Modal A")}>Open Modal A</p>
<Modal displayModal={modal} closeModal={selectModal}>
<div>modal1</div>
<div onClick={() => setModal1("modal a1")}>Open second modal</div>
<Modal displayModal={modal1} closeModal={setModal1}>
<div>modal2</div>
<div>Second modal</div>
</Modal>
</Modal>
</div>
);
}
export default App;
Top comments (0)