Skip to content
Advertisement

How to get form values from multiple child components?

I have a large HTML Form and it has multiple fields in multiple components.

All these components are in a Parent Component.

How Can I submit a form and getting values from all child components?

<form>
  <Col md={6} className="mb-3">
     <SameDay />
  </Col>
  <Col md={6} className="mb-3">
     <International />
  </Col>
  <Col md={6} className="mb-3">
     <OutBondTracking/>
  </Col>
  <Col md={6} className="mb-3">
     <FulfilmentOptions />
  </Col>
  <button
    type="button"
    className="btn btn-primary mr-2"
    onClick={() => this.submitHandler()}
  >
    Submit
  </button>
</form>

Advertisement

Answer

you can pass a handler function in the subcomponents(child components) that gets triggered when anything changes and updates the state in the parent component eg:

class ParentComponent extends React.Component {

  constructor(props) {
    super(props);

    this.state = {
      data: {} . // form data
    }

  }

  onChangeHandlerFn = (data) => {
    // update the state;
    this.setState({ data })
  }

  submitHandler = () => {
    // your handler function
     post your data from the state (data)
  }


   render() {
     return (
        <form>
          <Col md={6} className="mb-3">
                       <SameDay />
                    </Col>
                    <Col md={6} className="mb-3">
                        <International onChangeHandlerFn={this.onChangeHandlerFn}/>
                    </Col>
                    <Col md={6} className="mb-3">
                        <OutBondTracking onChangeHandlerFn={this.onChangeHandlerFn} />
                    </Col>
                    <Col md={6} className="mb-3">
                        <FulfilmentOptions onChangeHandlerFn={this.onChangeHandlerFn} />
                    </Col>
                  <button type="button" className="btn btn-primary mr-2"  onClick= 
                 {this.submitHandler}>Submit</button>
       </form>
     );
   }
}

handler function onChangeHandlerFn={this.onChangeHandlerFn}, should be called if anything is changed in the child components, which intern updates the state of the parent component

Hope this helps !!

User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement