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!
Controller
instead ofregister
solved my issue, but I need to usegetValues()
calls for my radio button inside myonSubmit
method, otherwise it doesn't work. Thank you for your help. :) – Fulminous