Reputation: 23
im using react and i try to make form with custom submit button (with div)
but when i submit the form the page automatically refreshes, despite e.preventDefault
my code :
<form onSubmit={e => e.preventDefault()} className="form">
<div
onClick={e => {
e.preventDefault();
document.querySelector(".form").submit();
}}
id="button"
>
Submit
</div>
</form>
demo on code sandbox : https://codesandbox.io/s/bitter-pond-9fcnr
Upvotes: 1
Views: 619
Reputation: 23
I came up with this solution but I don't know if it is the best idea:
<form onSubmit={e => e.preventDefault()} >
<div
onClick={e => {
e.preventDefault();
document.querySelector(".hidden-button").click();
}}
id="button"
>
Submit
</div>
<button type="submit" id="hidden-button"/>
</form>
and also in css :
#hidden-button{
display: none;
}
Upvotes: 0
Reputation: 118289
As per the spec
form . submit()
Submits the form, bypassing interactive constraint validation and without firing a submit event.
This is why your onSubmit
callback doesn't get called, and page is getting refreshed as per the normal browser behaviour.
I'd suggest a work around in this case:
import React, { useRef } from "react";
import ReactDOM from "react-dom";
function App() {
const submitEl = useRef(null);
const handleFormSubmit = e => {
e.preventDefault();
};
const handleBtnClick = e => {
e.preventDefault();
submitEl.current.click();
};
return (
<div className="App">
<form onSubmit={handleFormSubmit} className="form">
<div onClick={handleBtnClick} id="button">
Submit
</div>
<input
ref={submitEl}
name="submit"
type="submit"
style={{ display: "none" }}
/>
</form>
</div>
);
}
const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);
Upvotes: 3