0

I have a button such that when it is pressed, it'll update its parent's state, which will in turn then change the text of the child element of the parent.

I have a SiteContainer class, which serves as the parent class, and a NavBar class, which is the child. The NavBar class contains two elements, one being a button and the other being a label. I want it such that when I press the button, it'll call a function in the parent which will update its state, and then update the child element's state

My problem is that when I update the parent state after the button is clicked, the new state isn't passed down to the child to rerender.

Here is my SiteContainer class:

var SiteContainer = React.createClass({
    getRandomCustomerID: function() {
        console.log("getting random id");
        //just setting a test state for now, to fetch from server later
        this.setState({id: "test"});
    },
    getInitialState: function() {
        return {id: "customer_id"};
    },
    render: function() {
        return (
            <div>
                <NavBar id={this.state.id} getRandomCustomerID={this.getRandomCustomerID}/>
            </div>
        );
    }
})

Here is my NavBar class:

var NavBar = React.createClass({
    componentDidMount: function() {
        this.setState({id: this.props.id});
    },
    onClick: function() {
        console.log("next button pressed");
        this.props.getRandomCustomerID();
    },
    getInitialState: function() {
        return {id: this.props.id};
    },
    render: function() {
        return (
            <div className="row">
                <div className="col-md-6">
                    <h3>Customer ID: {this.state.id}</h3>
                </div>
                <div className="col-md-6">
                    <button className="btn btn-primary" onClick={this.onClick}>Next</button>
                </div>
            </div>
        );
    }
})

What am I doing wrong?

Ryan
  • 1
  • Please give a look into this question form more clarification http://stackoverflow.com/questions/25336124/reactjs-how-to-modify-child-state-or-props-from-parent – Fábio Luiz Jun 02 '16 at 19:15

1 Answers1

0

Fixed the problem, just changed it in the child class such that I call {this.props.id} rather than {this.state.id}, and removed the extra functions (componentDidMount, getInitialState) in the child.

Ryan
  • 1