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?