DEV Community

Saba beigi
Saba beigi

Posted on

5 1

custom Modal with javascript

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}>
          &times;
        </span>

        {props.children}
      </div>
    </div>
  );
}

export default Modal;
Enter fullscreen mode Exit fullscreen mode

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;
Enter fullscreen mode Exit fullscreen mode

AWS GenAI LIVE image

How is generative AI increasing efficiency?

Join AWS GenAI LIVE! to find out how gen AI is reshaping productivity, streamlining processes, and driving innovation.

Learn more

Top comments (0)

Billboard image

Create up to 10 Postgres Databases on Neon's free plan.

If you're starting a new project, Neon has got your databases covered. No credit cards. No trials. No getting in your way.

Try Neon for Free →

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay