I am using react-bootstrap but I am noticing some weird behavior on form submit.
I have a sign-in file which is a form in a modal
<Modal>
...
<Form
className="d-flex justify-content-center align-items-center flex-column"
onSubmit={onSubmitSignIn}
>
<Form.Group controlId="formBasicEmail">
<Form.Control
type="email"
placeholder="Enter email"
className={`signInputStyle ${
invalidEmail ? "invalidFieldStyle" : ""
}`}
value={email}
onChange={handleEmailValidation}
required
/>
<div>
<small className="errorFormText">
{invalidEmail ? "must be a valid email" : ""}
</small>
</div>
</Form.Group>
...
<div className="signupAcc">
Do not have an account?
<span onClick={() => setModalShow(true)}>SignUp</span>
<SignUp show={modalShow} onHide={() => setModalShow(false)} />
</div>
...
</Form>
</Modal>
In the sign-in component when you click on the SignUp span, it displays the second modal(which is for sign-up, therefore I have two modals now).
The sign-up modal has a form that is similar to that of the sign-in and they both have onSubmit function.
<Modal>
...
<Form
className="d-flex justify-content-center align-items-center flex-column"
onSubmit={onSubmitValue}
>
<Form.Group controlId="formGridFirstName1">
<Form.Control
placeholder="First Name"
required
name="firstname"
className={`signInputStyle ${
invalidateField.firstname ? "invalidFieldStyle" : ""
}`}
onChange={handleUserInput}
/>
<div>
<small className="errorFormText">
{invalidateField.firstname
? "must be at least three letters"
: ""}
</small>
</div>
</Form.Group>
...
</Form>
</Modal>
I noticed when I clicked on the button(type='submit') for the sign-up file it also triggers the onSubmit for the sign-in. My question is why is this behavior? Is it because both form fields are in the dom already? or something else? I really want to know the reason behind this behavior and how to resolve it. Thank you.
It is just native HTML button
behaviour. As stated on the documentation , the button element contains the type
attribute accepts 3 values: submit
, reset
, and button
. If the type
attribute is supplied with the submit
value, it will
Submit the current form data.
Deep inside the hood of, React-bootstrap's Form
Components, it probably makes use of the HTML Form Element, hence clicking on the button triggers the same mechanism for Form.submit() .
If you do not want this behaviour, you may simply remove the type
attribute ,or set the type attribute aas button ( type="button"
).
Make one of the buttons as type="button" and add an onClick action. the other one should work this way.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.