How to use Radio Button in React Hook Form v7?
Asked Answered
F

2

7

I'm working on an Ionic React App and I want to use React Hook Form and Yup Resolvers for submitting a form . My form contains a radio button and two other inputs.

I'm facing difficulties with the radio button. How should I write it in order to store its value and submit? Below you find my component. Even though I select one of the radio buttons , no value is stored.

import { yupResolver } from "@hookform/resolvers/yup";
import * as yup from "yup";

const validationSchema = yup.object().shape({
  firstName: yup.string().required("First name is required"),
  lastName: yup.string().required("Last name is required"),  
});

const AddUser = () => {

  const history = useHistory();
  const [type, seType] = useState("");
  const [firstName, setFirstName] = useState("");
  const [lastName, setLastName] = useState("");
 
const {
    register,
    handleSubmit,
    formState: { errors },
    getValues,
  } = useForm({
    mode: "onChange",
    resolver: yupResolver(validationSchema),
  });

  const onSubmit= () => {
   
    var data = {
            type: getValues("type"),
            firstName: getValues("firstName"),
            lastName: getValues("lastName"),
          };

    axios
      .post("/add-user", data)
      .then((response) => {
        return response.data;
      })
      .catch((error) => {
        setMessage(
          `You are already registered`    
        );
        setIserror(true);
       
      });
  };

  return (
    <React.Fragment>
   
      <IonPage className="ion-page" id="main-content">
     
        <IonContent className="ion-padding">
          <div>
            <h2>Add New User</h2>
            
            <form onSubmit={handleSubmit(onSubmit)}>
              
              <IonList>
                <IonRadioGroup
                 {...register("type")}
                >
                  <IonItem>
                    <IonLabel>Type 2</IonLabel>
                    <IonRadio value="2" slot="start" />
                  </IonItem>

                  <IonItem>
                    <IonLabel>Type 4</IonLabel>
                    <IonRadio slot="start" value="4" />
                  </IonItem>

                  <IonItem>
                    <IonLabel>Type 6</IonLabel>
                    <IonRadio slot="start" value="6" />
                  </IonItem>
                </IonRadioGroup>
              </IonList>
               
               <IonItem>
                <IonLabel position="floating">First name*</IonLabel>
                <IonInput
                {...register("firstName")}
                ></IonInput>
              </IonItem>

 
              <IonItem>
                <IonLabel position="floating">Last name*</IonLabel>
                <IonInput
                {...register("lastName")}
                ></IonInput>
              </IonItem>

              <br />
              <IonButton
                type='submit'
              >
                create
              </IonButton>
            </form>
          </div>
        </IonContent>
      </IonPage>
    </React.Fragment>
  );
};

export default AddUser;

package.json

"@hookform/resolvers": "^2.4.0",
"react-hook-form": "^7.1.1",
"yup": "^0.32.9"

Any help would be really appreciated!

Fulminous answered 7/5, 2021 at 12:57 Comment(0)
C
12

You need to use Controller instead of register to wrap <IonRadioGroup> because register only works for simple ionic components like <IonInput />.

<Controller
  control={control}
  name="type"
  render={({ field: { onChange, value } }) => (
    <IonList>
      <IonRadioGroup
        value={value}
        onIonChange={({ detail: { value } }) => onChange(value)}
      >
        <IonItem>
          <IonLabel>Type 2</IonLabel>
          <IonRadio value="2" slot="start" />
        </IonItem>
        <IonItem>
          <IonLabel>Type 4</IonLabel>
          <IonRadio slot="start" value="4" />
        </IonItem>
        <IonItem>
          <IonLabel>Type 6</IonLabel>
          <IonRadio slot="start" value="6" />
        </IonItem>
      </IonRadioGroup>
    </IonList>
  )}
/>

Edit React Hook Form - Ionic Radio Group

I also removed the getValues calls inside your onSubmit method, as the first parameter of this function already provides all registered form values.

Compilation answered 7/5, 2021 at 14:39 Comment(6)
Using Controller instead of register solved my issue, but I need to use getValues() calls for my radio button inside my onSubmit method, otherwise it doesn't work. Thank you for your help. :)Fulminous
Glad i could help! But just out of curiosity: why do you need getValues in onSubmit? If you register the radio button via Controller, it is included in your onSubmit callback. Have you looked at the CodeSandbox example from my answer - there the "type" form value is included in the onSubmit callback.Compilation
If I don't use getValues(), 'type' value is empty. See my log: {type: "", firstName: "g", lastName: "g"}. I saw your CodeSandBox example, it worked properly and to tell the truth I have no idea why it doesn't work without getValues() in my app.Fulminous
@Compilation How about using react-hook-form with pure HTML radio buttons? How to do it?Cite
@White159 For native HTML radio inputs you have to use register -> CodeSandboxCompilation
Switching to controller solved the issue. Thank youMicrophysics
U
0

You can avoid using a controler with:

<div>
    <input {...register("radio")} type="radio" value="A" />
    <input {...register("radio")} type="radio" value="B" />
    <input {...register("radio")} type="radio" value="C" />
</div>

See: https://react-hook-form.com/api/useform/register/#example

Utgardloki answered 21/4, 2023 at 4:9 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.