React Setting input value to value in a state array

1.8k Views Asked by At

I have a React-Bootstrap FormControl and I am trying to set the state with the following:

<FormGroup controlId={0} key={0} >
     <FormControl onChange={this.handleChange} value={this.state.form_answers[0]} />
 </FormGroup>

This.state.form_answers is being set in the constructor like so:

this.state = ({
  form_answers : ['foo','bar','foo-bar'],
});

My handle change function is updating the state with the following:

handleChange(event) {
  let form_answers = this.state.form_answers;
  form_answers[parseInt(event.target.id)] = event.target.value;
  this.setState({
    form_answers : form_answers,
  });
}

The state is being updated correctly, but the value displayed on the input field is not changing at all. I am also getting the following error message:

warning.js:36 Warning: FormControl is changing an uncontrolled input of type undefined to be controlled. Input elements should not switch from uncontrolled to controlled (or vice versa). Decide between using a controlled or uncontrolled input element for the lifetime of the component.

When I set FormControl to the following it works:

<FormGroup controlId={0} key={0} >
     <FormControl onChange={this.handleChange} value={this.state.form_answers[0]} />
 </FormGroup>


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

However, since I am creating multiple FormControl elements dynamically, the working solution is not feasible. Is it not possible to set the input value to an state index value? If it isn't possible, then could someone please give me advice on how best to update/set values for dynamically created input fields.

1

There are 1 best solutions below

4
On BEST ANSWER

The state is being updated correctly, but the value displayed on the input field is not changing at all

Are you sure? I did a local test and the state was NOT updating correctly because controlId is a property of FormGroup not FormControl. That is, FormControl will inherit the controlId value for its id if it's not set.

When I switched controlId to id in FormControl it worked as expected.