React how to update another component's state?

24,042

The basic idea of React is the unidirectional data flow. That means that data is only shared downwards from an ancestor component to its children via the child's properties. We leave Flux like architectures and event emitters out of the equation for this simple example as it's not necessary at all.

The ONLY way then to change a component's state from the outside is changing the props it receives in the parent's render method. so myState would actually live in ObjectB and be given to ObjectA as property. In your example that would 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>
        );
    }
});
Share:
24,042
lucky_start_izumi
Author by

lucky_start_izumi

Updated on February 03, 2020

Comments

  • lucky_start_izumi
    lucky_start_izumi over 4 years

    I am pretty new to react, trying to make some components 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'd like to update ObjectA's state from ObjectB. How could I in ObjectB call ObjectA's updateMyState method? Thanks!

  • lucky_start_izumi
    lucky_start_izumi over 8 years
    Thank you for the detailed answer.