2K01B5
2K01B5

Reputation: 1121

Inheriting State in react components

I'm trying to pass the state property 'val' down to the 'Counter' component and get 'Counter' to display its updated value when the mounted button is clicked. My problem is that I can pass the 'counterUpdate' function and call it from 'Counter', however I can't get the 'props.children' value to update within the view even though I'm updating 'state.val'. Any ideas and suggestions on why this might be would be much appreciated.

var App = React.createClass({
getInitialState: function(){
    return {
        val: 0   
    }
},
counterUpdate: function(){
    this.setState(function(previousState, props){
        return {
            val: previousState.val + 1   
        }
    })
},
mount: function(){
    ReactDOM.render(<Counter cu={this.counterUpdate} >{this.state.val}</Counter>, document.getElementById('a'))   
},
render: function(){
    return (
        <div>
            <button onClick={this.mount}>MOUNT</button>
            <div id="a"></div>
        </div>
        )
}
});

var Counter = React.createClass({
 render: function(){
    return (
            <button onClick={this.props.cu}>{this.props.children}</button>
        )
 }
});

ReactDOM.render(<App />, document.getElementById('content'));

Upvotes: 4

Views: 2361

Answers (1)

Jack
Jack

Reputation: 9548

I don't know the specifics of why your code is not working, but calling ReactDOM.render inside a component is odd way to be handling this. I would probably do something like the following:

var App = React.createClass({
getInitialState: function(){
    return {
        val: 0,
        showCounter: false, 
    }
},
counterUpdate: function(){
    this.setState(function(previousState, props){
        return {
            val: previousState.val + 1   
        }
    })
},
mount: function() {
    this.setState({showCounter: true});
},
render: function(){
    return (
        <div>
            <button onClick={this.mount}>MOUNT</button>
            {
              this.state.showCounter ? (<Counter cu={this.counterUpdate} >{this.state.val}</Counter>) : null
            }
        </div>
        )
}
});

Upvotes: 3

Related Questions