0

I am trying to update my state in ReactJS. To do this I have an input field in a Reactjs class. The field is automatically filled in with data from a parent class. The field looks like this:

           <input
            onChange={e => this.props.store.addLego(e)}
            name="piece"
            value={this.props.row.original.piece}
          />

The addLego function is designed to update my state and is in a MobX store. It looks like this:

 addLego = action("addLego", e => {
this[e.target.name] = e.target.value;
});

However, I can't actually edit the input field! Nothing changes in the field when I type! Thanks for your help!

Nespony
  • 857
  • 3
  • 14
  • 27
  • you have the value set to `this.props.row.original.piece`, the only way for the value of the input as you see it to change would be to update the value of `this.props.row.original.piece`. – Joe Lissner Jan 02 '18 at 19:25
  • the value of `this.props.row.original.piece` needs to change as a result of your `onChange` function. As long as that value doesn't change, the value in the input won't change. – tenor528 Jan 02 '18 at 19:26
  • Actual you're not updating the state of your component, but some store? Why not: this.setState({inputValue: e.target.value})} name="piece" value={this.state.inputValue} /> – Stefan van de Vooren Jan 02 '18 at 19:30
  • Have you checked the developer console for any Javascript or React exceptions? – tdurtsch Jan 02 '18 at 19:58

2 Answers2

1

If you set a value attribute to an <input> field that field becomes a controlled input. This means that whatever gets passed to value is rendered on the screen. In your case, if you are not updating this.props.row.original.piece the <input> field will never get a new value. I'll suggest to read this bit of React's documentation https://reactjs.org/docs/forms.html#controlled-components

It is basically suggesting to keep the new value somewhere (in the component's state for example) and set it back as a value to the field.

Krasimir
  • 12,605
  • 3
  • 34
  • 52
0

Follow this tutorial here will solve your problem. It's a good read too for handling single or multiple inputs

Basically, you'll need a state in the constructor

this.state = {value: ''};

Event handler to set the value every onchange

handleChange(event) {
    this.setState({value: event.target.value});
  }

And the setup for input

<input type="text" value={this.state.value} onChange={this.handleChange} />
Kim G Pham
  • 135
  • 6