1

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!

1 Answer 1

2

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);
},

Your Answer

Reminder: Answers generated by Artificial Intelligence tools are not allowed on Stack Overflow. Learn more

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.