1

I have two simple reactjs components with a parent-child relationship. The child contains an input with an onChange event and a callback to the parent to setState. When I run it, setState appears to work in the parent component, but the props passed into the child component don't appear to be updating. Any ideas? Here's a code snippet:

var FooInput = React.createClass({
  handleInputChange: function(e) {
    this.props.onInputChange(e.target.name, e.target.value);
  },
  render: function() {
    return (
      <div>
        <input name="foo" value={this.props.foo} onChange={this.handleInputChange} />
      </div>
    )
  }
})

var FooApp = React.createClass({
  getInitialState: function() {
    return {
      foo: 'bar',
    };
  },
  handleInputChange: function(key, value) {
    this.setState({key: value});
  },
  render: function() {
    return (
      <div>
        <FooInput
            foo={this.state.foo}
            onInputChange={this.handleInputChange} />
      </div>
    );
  }
});

In the example above, the value of input in the FooInput child component stays as "bar" despite the fact that handleInputChange is triggered in the FooApp parent component and foo is passed into the child component via this.props. Why doesn't the input value change to reflect the new state?

1 Answers1

3

You're literally setting a state variable called key by doing this.setState({key: value}). If you want a variable key, you can use brackets:

handleInputChange: function(key, value) {
    this.setState({[key]: value});
}

Or create a new object.

handleInputChange: function(key, value) {
    const newState = {};
    newState[key] = value;
    this.setState(newState);
}
ZekeDroid
  • 7,089
  • 5
  • 33
  • 59
  • I completely forgot that Javascript keys are interpreted as string literals. Thanks a lot for pointing it out, this was driving me nuts! – Henry Maddox Jun 27 '16 at 04:54