Reputation: 145
I am developing a web app using React JS. It has a page which consists of two forms Shipping Address and Billing Address. Now I want to submit these two forms via a single button.
<Form style={{ width: '300px' }}>
<Form.Group controlId="fullname">
<Form.Control
style={InputStyle}
required
type="text"
placeholder="Full Name *"
value={fullname ? fullname : ""}
onChange={(e) => setField('fullname', e.target.value) }
></Form.Control>
</Form.Group>
<Form.Group controlId="address">
<Form.Control
style={InputStyle}
required
type="text"
placeholder="Address *"
value={address ? address : ""}
onChange={(e) => setAddress(e.target.value)}
></Form.Control>
</Form.Group>
<Form.Group as={Col} controlId="formGridZip">
{/* <Form.Label>Zip</Form.Label> */}
<Form.Control
required
type="numeric"
style={InputStyle}
value={postalCode ? postalCode : ""}
placeholder="Postal Code *"
onChange={(e) => setPostalCode(e.target.value)}
/>
</Form.Group>
<Form.Group as={Col} md="4"controlId="Mobile">
<Form.Control
required
type="numeric"
style={InputStyle}
value={mobile ? mobile : ""}
placeholder="Mobile Number *"
onChange={(e) => setMobile(e.target.value)}
/>
</Form.Group>
</Form>
Above one is shipping address and billing address is similar to this.
Is it really feasible to import these two forms in a page and the submit via a single button? Or should I use leave behind this approach.
<div>
<Shipping Address />
<Billing Address />
<Button type="submit" />
</div>
Upvotes: 0
Views: 5077
Reputation: 726
You can pass a state variable maintained by the parent component (something like submitForm
) as a prop to both the form components. Inside componentDidUpdate
methods of the form components, watch for a change in the value of the submitForm
prop, if it is true
, invoke the respective form submit actions.
Initially, in the parent component the value of submitForm
would be false
, then on onClick
event of the submit button of your parent component, change the value of submitForm
to true
. The componentDidUpdate
methods of the form components will notice the prop update, and invoke the submit actions as you had intended to.
Let me know if I'm not clear enough, I will add some code snippets.
Upvotes: -1
Reputation: 1320
Well, If you are sending both these forms in the same request, then you can make a form object inside the parent component and then pass the form object to the children form and bind it. And then on Submit just post the data which is in the object.
If these forms need to submit to different URLs then you can just pass a function as a prop into child components and just call that function from the parent component when submit button is clicked.
Please let me know if the situation is other than I mentioned above.
Upvotes: 2