← coderrocketfuel.com

Show a Confirm Window Before Executing a Function in React.js

How can you show a confirmation window before executing a function in React.js?

Where a user is prompted with a window where they can confirm or cancel the action. And the React.js application will wait to proceed until the user has selected an option.

You can do this with the window.confirm() method:

function handleUserAction() {
  if (!window.confirm("Are you sure you want to do that?")) {
    return;
  } else {
    console.log("Make request to the API");
  }
}

window.confirm() returns true if the user confirms or false if the user cancels.

If the user selects the cancel option, the function is configured to return without doing anything. And if the user confirms the action, the function will proceed forward.

In a Google Chrome browser, that would produce a window that looks like this:

Google Chrome Confirm Window

Here's an example using this function when a <button> element is clicked:

import React from "react";

export default function HomePage() {
  function handleDeleteRequest() {
    if (!window.confirm("Are you sure you want to delete that?")) {
      return;
    } else {
      console.log("Make request to the API");
    }
  }

  return (
    <button onClick={ handleDeleteRequest }>
      Delete
    </button>
  );
}

When the delete button is clicked, a confirmation window is shown with the "Are you sure you want to delete that?" message.

If the user confirms that they want to delete, the API request will be made. If not, the function will be stopped before that happens.

Thanks for reading and happy coding!