I have 3 components in React, one acts as a container which passes down my child components to be rendered in a form. When the form is submitted I want to get each of the child components in my parent component, loop through each one, create an object my server expects then send the list of objects back to the server. I am struggling to access the child components in my onSubmit function in my parent component.
Here is my parent component
ParentFixturesComponent.js
class ParentFixturesComponent extends Component {
constructor() {
super();
this.state = {
numChildren: 0,
};
}
onAddMatch() {
this.setState({
numChildren: this.state.numChildren + 1
});
}
onSubmit(e) {
e.preventDefault();
// loop through the child components
// create a match object with them
// var match = {
// id: uuid(),
// title: uuid(),
// start: e.something,
// end: e.something,
// };
console.log("submit works");
}
render() {
const children = [];
for (let i = 0; i < this.state.numChildren; i += 1) {
children.push(<SingleMatchForm key={uuid()}/>)
}
return (
<Fixtures addMatch={this.onAddMatch.bind(this)} save={this.onSubmit.bind(this)} >
{children}
</Fixtures>
);
}
}
export default ParentFixturesComponent;
Component which holds my form where my parent renders all my children components
ChildFixturesContainer.js
class Fixtures extends Component {
constructor(props) {
super(props);
this.handleChange = this.handleChange.bind(this);
}
handleChange(name) {
this.console.log(this.props);
}
render() {
return (
<div className="tray tray-center">
<div className="row">
<div className="col-md-8">
<div className="panel mb25 mt5">
<div className="panel-heading">
<span className="panel-title">Fixtures</span>
</div>
<div className="panel-body p20 pb10">
<div id="fixture-parent" onChange={this.handleChange.bind(this)}>
{this.props.children}
</div>
</div>
<div className="section-divider mb40" id="spy1"> </div>
<button className="btn btn-primary tm-tag" onClick={this.props.addMatch}>Add Match</button>
<button className="btn btn-alert tm-tag" onClick={this.props.save}>Save</button>
</div>
</div>
</div>
</div>
);
}
}
export default Fixtures;
And finally my child individual form component.
SingleMatchComponent.js
class SingleMatchForm extends Component {
constructor() {
super();
this.state = {
startDate: moment()
};
}
handleChange(date) {
this.setState({
startDate: date
});
}
render() {
return (
<div className="row">
<div key={this.props.id} className="form-group">
<label className="control-label col-md-2">New Match</label>
<div className="col-md-6">
<DatePicker
selected={this.state.startDate}
onChange={this.handleChange.bind(this)}/>
<div className="section-divider mb40" id="spy1"> </div>
</div>
</div>
</div>
);
}
}
export default SingleMatchForm;