Show a confirm window before calling a function in React.js?

nick asked this question 1 year, 6 months ago
nick on Dec 5, 2021

On my website, there is an option where a user can delete their post.

To do that, they click on a "Delete" button and a request is sent to the my REST API that deletes the post from the database.

How can I show a confirmation window to the user before the request is sent to the REST API? And if they select to cancel their decision to delete the post, how can I stop the request from being sent?

1 suggested answers
looper003 on Dec 7, 2021

You can prompt the user to confirm an action using:

window.confirm("Are you sure you want to do that?")

That will stop all other code from being executed on the page and will show a pop-up window like the image below.


If the user confirms the action, the window.confirm() function will return a true value. Otherwise, a false value is returned instead.

Using this method, you can update your function to this:

function deleteRequest() {
  if (!window.confirm("Are you sure you want to do that?")) {
  } else {
    // make request to the REST API

When this function is called, the user will be prompted and asked to confirm the action.

If the user cancels the action, the function is ended using return and the request is not sent to the REST API.

And if the user confirms the action, the function goes on as normal.

0 replies