React how to update another component state?

I'm fairly new to react, trying to get some components to work. I have

ObjectA:React.createClass({ propTypes: { ... }, getInitialState: function() { return { myState: null } }, updateMyState: function(value) { this.setState({ myState: value }) } render: function() { return (<div className="my-class">'hello' +{this.state.myState}</div>); } }); ObjectB:React.createClass({ propTypes: { ... }, render: function() { return (<div className="my-class"><ObjectA / > </div>); } }); 

I want to update an ObjectA object from ObjectB. How could I call the ObjectA updateMyState method in ObjectB? Thanks!

+8
javascript reactjs web react-native frontend
source share
1 answer

The main idea of ​​React is a unidirectional data stream. This means that data is transferred only from the ancestor component to its children through child properties. We leave Flux as the architectures and event emitters of the equation for this simple example, since it is not required at all.

The only way to change the state of a component from the outside is to change the attribute that it receives in the parent rendering method. therefore myState will actually live in ObjectB and will be assigned to ObjectA as a property. In your example, it will look like this:

 ObjectA:React.createClass({ propTypes: { ... }, render: function() { return (<div className="my-class">'hello' +{ this.props.name }</div>); } }); ObjectB:React.createClass({ propTypes: { ... }, getInitialState: function() { return { name: null } }, onNameChange: function(newName) { this.setState({ name: newName }) }, render: function() { return ( <div className="my-class"> <ObjectA name={ this.state.name } /> </div> ); } }); 
+15
source share

All Articles