How to use Radio Button in React Hook Form v7?

Viewed 14292

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!

1 Answers

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.

Related