I’m using react-hook-form for form validations. When I use normal DOM as Input element the reset works fine. But when I use IonInput as Controller element, after submission Input values cleared but the errors are still visible.
import { IonItem, IonLabel, IonText, IonInput, IonButton, IonGrid, IonRow, IonCol } from '@ionic/react';
import React, { useRef, useState, useEffect, useContext } from 'react';
import { useForm, Controller } from "react-hook-form";
const defaultValues = {
name: "",
email: ""
};
const ContactForm: React.FC = () => {
const { control, errors, handleSubmit, reset, formState } = useForm({
defaultValues: { ...defaultValues },
mode: "onChange"
});
const showError = (_fieldName: string, msg: string) => {
let error = (errors as any)[_fieldName];
return error ? (
(error.ref.name === _fieldName)? (
<div className="invalid-feedback">
{error.message || `${msg} is required`}
</div>
) : null
) : null;
};
const onSubmit = (data: any, e: any) => { console.log(data);
console.log(errors);
// reset({ name: '', email: '', company: '', phone: '', message: '' });
reset(defaultValues);
}
return (
<form onSubmit={handleSubmit(onSubmit)}>
<IonGrid>
<IonRow>
<IonCol>
<IonItem class="ion-no-padding">
<IonLabel position="stacked">Name <IonText color="danger">*</IonText></IonLabel>
<Controller
as={IonInput}
control={control}
onChangeName="onIonChange"
onChange={([selected]) => {
return selected.detail.value;
}}
name="name"
placeholder="John"
defaultValue=""
rules={{
required: true,
pattern: {
value: /^[A-Z0-9 ]{2,25}$/i,
message: "Invalid Name"
}
}}
/>
</IonItem>
{showError("name", "Name")}
</IonCol>
</IonRow>
<IonRow>
<IonCol>
<IonItem class="ion-no-padding">
<IonLabel position="stacked">Email <IonText color="danger">*</IonText></IonLabel>
<Controller
as={IonInput}
control={control}
onChangeName="onIonChange"
onChange={([selected]) => {
return selected.detail.value;
}}
name="email"
placeholder="john@example.com"
rules={{
required: true,
pattern: {
value: /^[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,4}$/i,
message: "Invalid Email Address"
}
}}
/>
</IonItem>
{showError("email", "Email")}
</IonCol>
</IonRow>
</IonGrid>
<IonButton className="ion-margin-top" expand="block" type="submit">
Submit
</IonButton>
</form>
);
};
export default ContactForm;
Anyone can help this?