I'm trying to learn how to implement a React form (ES6 syntax) and pass the onChange events for each field up to a controller parent component which is responsible for updating the state. This works fine for standard html elements, however I am trying a pre-canned Datepicker (https://www.npmjs.com/package/react-bootstrap-date-picker) for a date field and can't readily pass the event back up to the parent in the same way. Is there a simple way to address this?
Controller Component
class Parent extends React.Component {
constructor (props) {
super(props);
this.state = {job: ''}
}
setJobState(event) {
var field = event.target.name;
var value = event.target.value;
this.state.job[field] = value;
this.setState({job: this.state.job});
}
render () {
return <Child onChange={this.setJobState.bind(this)} />
}
}
Child Component
class Child extends React.Component {
constructor (props) {
super(props);
}
render () {
<form>
<input type="text" name="jobNumber" onChange={this.props.onChange} />
<DatePicker name="dateCmmenced" onChange={this.props.onChange} />
</form>
}
}
onChangehandler correctly, but theonChangehandler for theDatePickeris called with two parameters:valueandformattedValue(see here: github.com/pushtell/react-bootstrap-date-picker#datepicker-). In yourChildcomponent just set different handlers for the twoonChangeevents, that are able to handle the difference in arguments. - forrertthis.state.job[field] = valueis not how you should update your state. Always make state changes by callingthis.setState. - forrertDatePickercomponent, the best I could come up with was the following, but I am a js novice, so yeah:setJobState(event) { if (typeof event === 'object') { var field = event.target.name; var value = event.target.value; this.state.job[field] = value; } else if (typeof event === 'string') { this.state.job.dateCommenced = event; } return this.setState({ job: this.state.job }); }- Han Uman