arkoak arkoak - 3 months ago 9
Javascript Question

Modify state data for non-child react component

I have two , mostly independent react classes

var User = React.createClass({
....
updateGameScore: function(){ this.game1.score = .... }
render: function(){ return ( <div>{this.state.totalScore}</div>);
});


var Game = React.createClass({
....
updateUserScore:function(){ how to access/modify parent here??? },
render: function(){ return ( <div>{this.state.score}</div>);
});


I need to be able to update the user totalScore when game score changes and vice versa based on some formula (irrelevant here). The components are such that game is nested in the user as a child component but cannot be vice versa. Change in user score can update game score by passing down the variable using
this.state(..)
, however when game score changes, what way can I use to update the correct parent User score (there can be more than one users at a time)

Answer

You can pass a handler function from User to Game via props:

var User = React.createClass({
    ...
    handleScoreChange: function(newScore) {
        this.setState({totalScore: newScore});
    }

    render: function () {
        return (
            <Game handleScoreChange={this.handleScoreChange.bind(this)} />
        )
    }
});

var Game = React.createClass({
    ...
    updateUserScore: function() {
        this.props.handleScoreChange(this.state.score); 
    }
}
Comments