Reputation: 37238
I have an options page comonent. This component is composed of row. Each row is a setting. That setting is either a select, check, radio, or custom element. This component is updated in two ways:
When #2 happens, meaning the user manipulated component, I want the onChange on the top most component to fire. Is there an event like this? I cant seem to find it in component life cycle.
Reason why I cannot use componentDidUpdate
, is because when user triggers onChange of row, I need to make a request to server with the new info. If AJAX tells the compoent to update, onComponentDidUpdate will trigger, but I don't need to make an AJAX request.
Upvotes: 3
Views: 5246
Reputation: 66
You can do that by passing a callback from Top Component on its Child component Property. The callback then will be invoked by Child component onChange event by using this.props.callbackName(). For example
TopComponent.js
// import react (i'm using es2015)
// but the concept is the same whether you use it or not
import React, {Component} from 'react'
class TopComponent extends Component {
// the callback
onChildComponentChange(){
doAjax().then(function(data){
this.setState({foo: data})
})
}
render(){
return (<ChildComponent onPropertyChange={this.onChildComponentChange}) />
}
}
ChildComponent.js
import React, {Component} from 'react'
class ChildComponent extends Component {
onChangeHandler(){
// from this handler we call the top component callback
this.props.onPropertyChange(data) // the name of props we pass from top component
}
render(){
return (<RowComponent onClick={this.onChangeHandler}/>)
}
}
Upvotes: 5