I'm building a form using Ionic 6, React 18 and react-hook-form 7.37.0.
My form includes a field where a datetime needs to be set, which is implemented with IonDatetime
.
Using minuteValues
parameter I limit the user to select minutes values in 5 minutes increments. This works fine. However, IonDatetime is including a default time that does not follow this restriction, any minute value can appear as default. I'd like to have a valid minute value as a default value. I have tried to set a default valid time with value
parameter but I've found out that it interferes with the use of the watch
function of react-hook-form
.
If I watch
the IonDatetime field, I cannot set any other value than the default value. Here there is a minimal example of this.
I also leave here the most relevant part of the code.
const birthTime = watch("birthTime");
<IonItem {...register("birthTime")} button={true} id="open-datetime">
<IonLabel>Birth time</IonLabel>
{birthTime !== "" ? (
<IonText>
{format(parseISO(birthTime!), "dd MM yyyy HH:mm")}
</IonText>
) : (
<IonText class="placeholder">Select a date</IonText>
)}
<IonModal ref={modal} trigger="open-datetime">
<IonContent>
<IonDatetime
min="2022-09-18T12:23"
max="2022-10-12T17:22"
value="2022-09-23T15:00"
minuteValues="0,5,10,15,20,25,30,35,40,45,50,55"
onIonChange={(ev: any) => {
setValue(
"birthTime",
dateFormat(
(ev.detail.value as unknown) as Date,
"yyyy-mm-dd'T'HH:MM"
)
);
}}
/>
<IonButton
onClick={() => {
dismiss();
}}
>
Close
</IonButton>
</IonContent>
</IonModal>
</IonItem>
To set the default value of an IonDatetime component while using the watch function from react-hook-form, you can pass the default value as the defaultValue prop to the IonDatetime component.
This is a basic idea, i am not using your code,sorry
import { IonDatetime } from "@ionic/react";
import { useForm, Controller } from "react-hook-form";
function MyForm() {
const { watch } = useForm();
const defaultValue = watch("myDateTimeInput");
return (
<form>
<Controller
as={<IonDatetime />}
control={control}
name="myDateTimeInput"
defaultValue={defaultValue}
/>
</form>
);
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.