Skip to content

Instantly share code, notes, and snippets.

@yordanzhelevdev
Created June 1, 2018 08:22
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save yordanzhelevdev/2805531720096725eae6df587fbd8298 to your computer and use it in GitHub Desktop.
Save yordanzhelevdev/2805531720096725eae6df587fbd8298 to your computer and use it in GitHub Desktop.
Parent to Child - React
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>
}
}
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