Build a confirmation modal with dialog
Close a native confirmation dialog with method=dialog and read the button choice from returnValue.
You need a confirm box: "Delete this project?" with Cancel and Delete. You reach for a boolean in component state, an onClick on each button, and a function that closes the modal and passes the answer back. That is three pieces of code for something the browser already does.
A <dialog> opened with showModal() and a <form method="dialog"> inside it give you the same result with one listener.
The markup
Put the form inside the dialog and give each button a value. Name the dialog with its question and give Cancel the initial focus.
<button id="open">Delete project</button>
<output id="result"></output>
<dialog id="confirm" aria-labelledby="confirm-title">
<form method="dialog">
<p id="confirm-title">Delete this project?</p>
<button value="cancel" autofocus>Cancel</button>
<button value="delete">Delete</button>
</form>
</dialog>The dialog is hidden on load, so you see only the "Delete project" button.
The script
Open it with showModal(). Read the answer in the close event. Clear returnValue before each open so an old answer cannot carry over.
const dialog = document.querySelector('#confirm')
const result = document.querySelector('#result')
document.querySelector('#open').addEventListener('click', () => {
dialog.returnValue = ''
dialog.showModal()
})
dialog.addEventListener('close', () => {
result.textContent = dialog.returnValue
})Click "Delete project" and the dialog appears over the page, with the rest of the page inert. Click Delete and it closes, and the <output> reads delete.
What the form does
A form whose method is dialog is not submitted to a server. Per MDN, it closes the dialog, keeps the form controls' state without submitting it, and sets returnValue to the value of the button that was activated.
I ran the page in Chromium and clicked each way out:
- Delete button:
returnValueisdelete - Cancel button:
returnValueiscancel - Escape key: the dialog closes and
returnValueis the empty string
The Escape case needs no handler. The close event still fires, and the empty returnValue you set before opening tells you nobody picked a button. Treat the empty string as cancel and you have covered all three exits.
The HTML spec says the returnValue getter returns the last value it was set to. The reset line keeps an answer from one open from leaking into the next.
A submit button outside the form must still belong to it. While it is inside the dialog, you can associate it using a form attribute that matches the form’s ID. If you use formmethod="dialog", it overrides the associated form’s method. Calling dialog.close('delete') from code also sets returnValue.
Put your real work in the close listener and branch on dialog.returnValue: delete the project when it equals delete, and do nothing otherwise. It runs once per close, whichever way the user left.