I have following react classes:
var FormBox = React.createClass({
render: function() {
return (
<h1>Forms:</h1>
<InternalForm name="foo" />
<InternalForm name="bar" />
<form className="externalForm" onSubmit={this.handleSubmit}>
<input type="submit" value="Post" />
</form>
);
}
})
var InternalForm = React.createClass({
render: function() {
return (
<h1>{this.props.name}</h1>
<form className="internalForm">
<input type="text"/>
/* form strucure based on props*/
</form>
);
}
})
After external form submition, I need to get a json that contains values of intertal forms like
{'foo':{},'bar':{}}
I guess that FormBox needs to call onSubmit on each internal form, but it doesn't feel quite right.
How to perform it? Thanks
You are right, calling onSubmit on each Subcomponent is not the way you would do this in react. Instead of this, you should hold a state object in your external containing the values of foo and bar. To keep them in sync, you should pass a callback to the child forms so they update the state when needed. Then when submitting you only need to use the external form's state.
Something like this:
var FormBox = React.createClass({
getInitialState: function() {
return {
foo: null,
var: null
};
},
onChildChange: function(childName, childValue){
let newState = {};
newState[childName] = childValue;
this.setState(newState)
},
render: function() {
return (
<h1>Forms:</h1>
<InternalForm name="foo" onFormChange={this.onChildChange}/>
<InternalForm name="bar" onFormChange={this.onChildChange} />
<form className="externalForm" onSubmit={this.handleSubmit} onChange={this.onChildChange.bind(this, 'bar')}>
<input type="submit" value="Post" />
</form>
);
}
})
var InternalForm = React.createClass({
onFormChange: function(e) {
this.props.onFormChange(this.props.name, e.target.value);
}
render: function() {
return (
<h1>{this.props.name}</h1>
<form className="internalForm">
<input type="text" onChange={this.onFormChange}/>
/* form strucure based on props*/
</form>
);
}
})
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With