javascriptreactjsdialogmodal-dialog

How to close dialog in React?


I have a general DialogueWindow component:

function DialogueWindow({elements}) {

  return (

    <div className="backdrop">

      <dialog className="dialogue-window">

        {elements}

      </dialog>

    </div>
  )
}

export default DialogueWindow

It displays inside of it whatever elements it gets passed down to. Currently I'm passing on a FileUploader element, that has a cancel button for the user to close the dialog.

In App.js:

<DialogueWindow
     elements={
        <FileUploader/>
     }
/>

In FileUploader:

function FileUploader() {

  ...

  return (

    <div className="file-uploader">

        ...

        <div className="file-uploader-button-container">

            <button>
                Upload
            </button>

            <button>
                Cancel
            </button>

        </div>

    </div>
  )
}

export default FileUploader

I have seen that in standard javascript you call document.getElementById() to fetch the dialog element, and then call the close() method on it. But how does this work in React?


Solution

  • The typical way to do this is by adding a state variable that determines if <DialogueWindow /> is rendered or not.

    The state variable will be controlled through a function, that needs to be passed from the parent to where the Cancel button is.

    You may also need to call onClose after a successful Upload, to prevent the dialog from showing forever.

    App.js:

    import { useState } from "react";
    import DialogueWindow from "./DialogueWindow";
    import FileUploader from "./FileUploader";
    
    function App() {
      const [showUploader, setShowUploader] = useState(true);
    
      const closeUploader = () => setShowUploader(false);
    
      return (
        <div>
          {showUploader &&
            <DialogueWindow
              elements={<FileUploader onClose={closeUploader} />}
            />
          }
        </div>
      );
    }
    

    FileUploader.js:

    function FileUploader({ onClose }) {
      ...
      return (
        <div className="file-uploader">
          ...
          <div className="file-uploader-button-container">
            <button>Upload</button>
            <button onClick={onClose}>Cancel</button>
          </div>
        </div>
      );
    }
    export default FileUploader;