Search code examples
javascriptreactjsformsradio-buttonreact-state-management

React setState() not working on radio field handleInput method


I'm working on a radio submit method in a React app.

handleSelect = e => {
    const key = e.target.name;
    const value = e.target.id;
    this.setState({ [key]: value});
    console.log(this.state);
  }

Here is the radio field in question:

<div className="answer">
                      <Input type="radio"
                        id="day2AnswerA"
                        name="day2CorrectAnswer"
                        value={this.state.day2CorrectAnswer}
                        onChange={this.handleSelect}
                      />

And here is my state:

  state = {
    rocketName: '',
    className:'',

    day2QuestionName: '',
    day2ReviewText: '',
    day2QuestionText: '',
    day2AnswerA: '',
    day2AnswerB: '',
    day2AnswerC: '',
    day2AnswerD: '',
    day2CorrectAnswer: '',
  }

This will be part of a larger form with multiple radio fields, all with the same name attribute so that only one can be selected at a time.

I am trying to make the state update as soon as the user selects a radio field, for example if the user clicks on the above shown radio field then I want the day2CorrectAnswer property of the state to be immediately updated to be day2AnswerA.

Why is this not working?


Solution

  • Looking at your input I can see a circular state problem - the value of each radio input cannot simply be the state value it must have an actual value instead - probably a string value like value="The Big Blue Bear" and what you want to do to ensure the input is controlled is to have it's checked state evaluate if the state value for day2CorrectAnswer is equal to the value of this input.