2

I have a form in my React project. I would like to call confirm() if the user clicks the submit button. I tried it like this:

<form onSubmit="return confirm('Are you sure?')">...</form>
<button type="submit" onClick="return confirm('Are you sure?')">Submit</button>
<form onSubmit={()=>window.confirm('Are you sure?')}>...</form>
<button onClick={() => window.confirm("Are you sure")}>Submit</button>

Unfortunately nothing happens, the form is submitted without the alert. React somehow removes the onClick and onSubmit. How is it possible to avoid that?

Iter Ator
  • 8,226
  • 20
  • 73
  • 164

4 Answers4

6
import React from "react";
import "./styles.css";

export default function App() {

  const handleSubmit = (e) => {
    e.preventDefault();
    const answer = window.confirm("are you sure?");
    if (answer) {
      // Save it!
      console.log("Thing was saved to the database.");
    } else {
      // Do nothing!
      console.log("Thing was not saved to the database.");
    }
  };
  return (
    <div className="App">
      <form onSubmit={handleSubmit}>
        ...
        <button type="submit">Submit</button>
      </form>
    </div>
  );
}

i believe you are looking for the confirm method of javascript

https://codesandbox.io/s/flamboyant-lake-hl5rb?file=/src/App.js

Rob Terrell
  • 2,398
  • 1
  • 14
  • 36
  • as stated below you can also use state variables as booleans and if the submitting variable is set to false (a user hits no) the submission will not fire – Rob Terrell Feb 09 '21 at 19:07
  • Very similar, but I did `if(!answer){ return undefined; }` – Narek Jun 29 '21 at 23:29
2

You would need to use JSX for that. The syntax is as follows:

      <form onSubmit={() => window.confirm("Are you sure?")}>
        <input name="dsad" />
        <button onClick={() => window.confirm("Are you sure")}>Submit</button>
      </form>

Using the confirm function is not the most elegant solution though, especially when you have React at your disposal. I certainly recommend using a state variable for it. If you're interested in learning how, let me know in the comments.

And this is how you do it the right way with React:

export default function App() {
  const [show_confirm_msg, setShowConfirmMsg] = useState(false);
  const form = useRef();

  const handleConfirm = (e) => {
    form.current.submit();
  };

  const handleConfirmMsg = (e) => {
    e.preventDefault();
    setShowConfirmMsg(true);
  };

  return (
    <div className="App">
      <h1>Hello CodeSandbox</h1>
      <h2>Start editing to see some magic happen!</h2>

      <form ref={form} onSubmit={handleConfirmMsg}>
        <input name="dsad" />
        <button onClick={handleConfirmMsg}>Submit</button>
      </form>
      {show_confirm_msg && (
        <div>
          <br /> Are you sure want to submit?{" "}
          <button onClick={handleConfirm}>Yes</button>
        </div>
      )}
    </div>
  );
}

Sandbox: https://codesandbox.io/s/confident-swirles-5cnio?file=/src/App.js


Added:

As pointed out by @EmileBergeron, you could accomplish this with even less code by doing this:

  const handleConfirm = (e) => {
    if(!show_confirm_msg){
      e.preventDefault();
      setShowConfirmMsg(true);
    }
  }

  return (
    <div className="App">
      <h1>Hello CodeSandbox</h1>
      <h2>Start editing to see some magic happen!</h2>

      <form onSubmit={handleConfirm}>
        <input name="dsad" />
        <button type="submit">Submit</button>
        {show_confirm_msg && (
        <div>
          <br /> Are you sure want to submit?{" "}
          <button type="submit" onClick={handleConfirm}>Yes</button>
        </div>
      )}
      </form>

    </div>
  );

I will leave the original Sandbox code as is for you to compare the two approaches as both are just different means to the same end.

codemonkey
  • 7,325
  • 5
  • 22
  • 36
0

I actually needed the form to submit as usual (not preventing nor providing a custom behavior) if the user confirms. So this is an alteration of @Rob Terrell answer:

import React from "react";
import "./styles.css";

export default function App() {

  const handleSubmit = (e) => {
    const answer = window.confirm("are you sure?");
    if (!answer) {
      // Do nothing!
      e.preventDefault(); // ------> We only prevent the behavior if negative answer
    }
  };
  return (
    <div className="App">
      <form onSubmit={handleSubmit}>
        ...
        <button type="submit">Submit</button>
      </form>
    </div>
  );
}
Antonio
  • 11,413
  • 6
  • 34
  • 48
-2

Create a new function (onConfirmation) and call it in onClick. Also create a flag and validate the flag before the submit.

In function onConfirmation, change the flag value to true.