最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - How is it possible to call confirm() before submitting a form in React? - Stack Overflow

programmeradmin0浏览0评论

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?

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?

Share Improve this question edited Feb 9, 2021 at 18:58 Iter Ator asked Feb 9, 2021 at 18:50 Iter AtorIter Ator 9,34121 gold badges89 silver badges183 bronze badges 3
  • Just add a callback instead of string to onSubmit. Btw, it is considered as very bad practice to use stringified js in react – captain-yossarian from Ukraine Commented Feb 9, 2021 at 18:53
  • @captain-yossarian I did that. See the edited question – Iter Ator Commented Feb 9, 2021 at 18:57
  • Does this answer your question? React - Preventing Form Submission – Emile Bergeron Commented Feb 9, 2021 at 19:18
Add a ment  | 

4 Answers 4

Reset to default 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

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 remend using a state variable for it. If you're interested in learning how, let me know in the ments.

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 acplish 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 pare the two approaches as both are just different means to the same end.

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>
  );
}

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.

发布评论

评论列表(0)

  1. 暂无评论