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?
JavaScript
x
22
22
1
<form>
2
<Col md={6} className="mb-3">
3
<SameDay />
4
</Col>
5
<Col md={6} className="mb-3">
6
<International />
7
</Col>
8
<Col md={6} className="mb-3">
9
<OutBondTracking/>
10
</Col>
11
<Col md={6} className="mb-3">
12
<FulfilmentOptions />
13
</Col>
14
<button
15
type="button"
16
className="btn btn-primary mr-2"
17
onClick={() => this.submitHandler()}
18
>
19
Submit
20
</button>
21
</form>
22
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:
JavaScript
1
44
44
1
class ParentComponent extends React.Component {
2
3
constructor(props) {
4
super(props);
5
6
this.state = {
7
data: {} . // form data
8
}
9
10
}
11
12
onChangeHandlerFn = (data) => {
13
// update the state;
14
this.setState({ data })
15
}
16
17
submitHandler = () => {
18
// your handler function
19
post your data from the state (data)
20
}
21
22
23
render() {
24
return (
25
<form>
26
<Col md={6} className="mb-3">
27
<SameDay />
28
</Col>
29
<Col md={6} className="mb-3">
30
<International onChangeHandlerFn={this.onChangeHandlerFn}/>
31
</Col>
32
<Col md={6} className="mb-3">
33
<OutBondTracking onChangeHandlerFn={this.onChangeHandlerFn} />
34
</Col>
35
<Col md={6} className="mb-3">
36
<FulfilmentOptions onChangeHandlerFn={this.onChangeHandlerFn} />
37
</Col>
38
<button type="button" className="btn btn-primary mr-2" onClick=
39
{this.submitHandler}>Submit</button>
40
</form>
41
);
42
}
43
}
44
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 !!