17

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!

1
  • @dvine multimedia's anwser is correct, and since react-native is based on react, you may want to take a look at react concepts: facebook.github.io/react/tips/… Commented Feb 3, 2016 at 8:44

1 Answer 1

23

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>
        );
    }
});
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you for the detailed answer.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.