Created
June 1, 2018 08:22
-
-
Save yordanzhelevdev/2805531720096725eae6df587fbd8298 to your computer and use it in GitHub Desktop.
Parent to Child - React
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Child extends React.Component { | |
constructor (props) { | |
super(props); | |
} | |
onFieldChange(event) { | |
// for a regular input field, read field name and value from the event | |
const fieldName = event.target.name; | |
const fieldValue = event.target.value; | |
this.props.onChange(fieldName, fieldValue); | |
} | |
onDateChange(dateValue) { | |
// for a date field, the value is passed into the change handler | |
this.props.onChange('dateCommenced', dateValue); | |
} | |
render () { | |
return <form> | |
<input type="text" name="jobNumber" onChange={this.onFieldChange.bind(this)} /> | |
<DatePicker onChange={this.onDateChange.bind(this)} /> | |
</form> | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Parent extends React.Component { | |
constructor (props) { | |
super(props); | |
this.state = {} | |
} | |
onChange(field, value) { | |
// parent class change handler is always called with field name and value | |
this.setState({[field]: value}); | |
} | |
render () { | |
return <Child onChange={this.onChange.bind(this)} /> | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment