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.