Home > OS >  ReactJS: RadioButton on reset
ReactJS: RadioButton on reset

Time:12-14

I have a form in which I have avRadioButton.

When I click on one of this radioButton, I save the value "S" or "N". But when I click on resetForm the value is set on empty string, but the radio button remains checked ( so if I click on submit form another time the radioButton's value is taken)

    const [formModel, setFormModel] = useState({
        //... other fields
        perFlgattivo: '',
      });
    
    const handleFormReset = e => {
        setFormModel({
        //... other fields
          perFlgattivo: '',
        });  
    }
    
    const handleChangeRadio = e => {
        const { name, value } = e.target;
        console.log("e.target ", e.target)
        setFormModel(prevState => ({
          ...prevState,
          [name]: value,
        }));
      };

and this is my radioButton in the form:

    <AvRadioGroup name="perFlgattivo" inline>
                        <Label id="perFlgattivo">Active</Trans>
                        </Label>
                        <br></br>
                        <AvRadio
                          id="perFlgattivo"
                          name="perFlgattivo"
                          data-cy="perFlgattivo"
                          label="Si"
                          value="S"
                          onChange={handleChangeRadio}
                          checked={formModel.perFlgattivo}
                        />
                        <AvRadio
                          id="perFlgattivo"
                          name="perFlgattivo"
                          data-cy="perFlgattivo"
                          label="No"
                          value="N"
                          onChange={handleChangeRadio}
                          checked={formModel.perFlgattivo}
                        />
                      </AvRadioGroup>

So my problem is when I'm trying to clear the value, because even if the formModel.perFlgattivo results an empty string, the value in the form remains checked

CodePudding user response:

This is a very rude solution, but checked={formModel.perFlgattivo.length > 0} will surely solve your problem.

Вut in general radio buttons should have boolean in value field. Try changing perFlgattivo default value to false and same on form reset.

  • Related