DWB
DWB

Reputation: 1554

Modify parent component state with key value

I have a child component in react, I would like to modify the parent component by calling on a function and giving both the key and value. Ideally it would go something like this

var FirstView = React.createClass({

handleStateChange: function(key, value) {
    this.setState({
        key: value
    });
}.

render: function() {
    return (
        <div>
            <SecondView onStateChange={this.handleStateChange} />
        </div>
    )
}
});

var SecondView = React.createClass({

handleClick: function() {
    this.props.onStateChange('theParent', 'isNowChanged');
},

render: function() {
    return (
        <div onClick={this.handleClick}>Stack Overflow</div>
    );
}
})

I'm not entirely sure whether this is the best way to go about this but I would like to pass in a key and a value like above. Unfortunately react doesn't want to play ball and the state of the parent doesn't seem to change. Is there a sensible way to go about this?

Thank you!

Upvotes: 1

Views: 239

Answers (1)

Mark
Mark

Reputation: 3163

Within your handleStateChange in FirstView, you have the following:

handleStateChange: function(key, value) {
    this.setState({
         key: value
     });
}.

The dictionary passed to setState uses the literal key rather than the variable key passed into the handleStateChange function. Try the following instead:

handleStateChange: function(key, value) {
    newState = [];
    newState[key] = value;
    this.setState(newState);
},

Upvotes: 2

Related Questions