Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

126
Visualizações
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 Respostas
Responde à pergunta

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda