Create a portal modal is not working in React

153 Views Asked by At

I want to create a modal using React Portal, so here I have created a showModal container for modal data, a Modal container we can use to control the Modal, and in index.html, I want a wrapper for myPortalModal class, through which I have to show modal to the whole application and give some CSS for the modal view. My doubt is that if I want to click on the click button, it will throw the error "Target container is not a DOM element." So how to resolve the problem and use the wrapper modal component to whole ove the applications here code is given below index.html, so if any modification of the code is required, please do that and why this error is happening even though I did all the right thing.

<!DOCTYPE html>
<html lang="en">
  <head>
  </head>
  <body>
    <div id="root"></div>
    <div class="myPortalModal"></div>
  </body>
</html>

and showmodal container code

import React from "react";
import ReactDOM from 'react-dom';
export default function ShowModal({closeModal}) {
 
  return ReactDOM.createPortal(
    <>
    <div className="modal-wrapper" onClick={closeModal}></div>
    <div className="modal-container">
      <h1>Heading</h1>
      <p>this is a modal , pls click close</p>
      <button onClick={closeModal}>Close</button>
      </div>
    </>,
    document.querySelector('.myPortalModal')
  );
}

Modal container code

import React, { useState } from "react";
import ShowModal from "./ShowModal";
export default function Modal() {
  const [showModal, setShowModal] = useState(false);
  const closeModal = () => setShowModal(false);
  return (
    <>
      <button onClick={() => setShowModal(true)}>Click</button>
      {showModal && <ShowModal closeModal={closeModal} />}
    </>
  );
}

and Modal is import in App components

1

There are 1 best solutions below

1
On

You change to return jsx

export default function ShowModal({closeModal}) {
 
  return <> {ReactDOM.createPortal(
    <>
    <div className="modal-wrapper" onClick={closeModal}></div>
    <div className="modal-container">
      <h1>Heading</h1>
      <p>this is a modal , pls click close</p>
      <button onClick={closeModal}>Close</button>
      </div>
    </>,
    document.querySelector('.myPortalModal')
  )} </>
}