Search code examples
javascripthtmlreactjsreact-bootstrap

Submit two forms with one button in react


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>


Solution

  • 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.