Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React how to update another component's state?

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!

like image 888
lucky_start_izumi Avatar asked Feb 03 '16 01:02

lucky_start_izumi


1 Answers

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>
        );
    }
});
like image 115
d-vine Avatar answered Nov 02 '22 05:11

d-vine