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>
CodePudding user response:
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>
)
}