Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

124
Views
Prevent HTML Modal Dialog from Closing

I want to use the <dialog> HTML element to create a modal. I'm trying to restrict the user's ability to close the modal under some circumstances, and tried to call e.preventDefault() when the dialog's onClose() is fired, however, that doesn't stop the dialog from closing.

What is the intended way to control whether modal dialog can be closed or not?

ReactDOM.render(
      <App />,
      document.getElementById("root")
 );

function App() {
  const modalRef = React.createRef()
  
  function handleClose(e) { // press escape button to trigger this
    e.preventDefault()
    console.log('closing')
  }
  
  return(
    <React.Fragment>
      <button 
        onClick={() => modalRef.current.showModal()}>
        Open modal
      </button>
      
      
      <dialog
        ref={modalRef}
        onClose={handleClose}>
        Hello world
      </dialog>
    </React.Fragment>
  )
}
<div id='root'></div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

There is no error in your code but in the dialog element you need to listen to onCancel event instead of onClose event.

ReactDOM.render(
      <App />,
      document.getElementById("root")
 );

function App() {
  const modalRef = React.createRef()
  
  function handleClose(e) { // press escape button to trigger this
    e.preventDefault()
    console.log('closing')
  }
  
  return(
    <React.Fragment>
      <button 
        onClick={() => modalRef.current.showModal()}>
        Open modal
      </button>
      
      
      <dialog
        ref={modalRef}
        onCancel={handleClose}>
        Hello world
      </dialog>
    </React.Fragment>
  )
}

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!