I have a form that I'm trying to add a React datetime picker to, but I'm also trying to integrate it with react-hook-form
so that it works with the rest of the form , but doesn't seem to work at all.
When the form is first rendered, the current date is not displayed in the date picker, only "----------" is displayed, and when I select a date from the popup window, the date in the field is not displayed either will change.
import { Controller, useForm } from 'react-hook-form' import DateTimePicker from 'react-datetime-picker' import 'react-datetime-picker/dist/DateTimePicker.css' import 'react-calendar/dist/Calendar.css' const Jobs = () => { const { control, register, handleSubmit, watch, formState: { errors } } = useForm(); const onSubmit = handleSubmit(async ({ firstname, startdate }) => { console.log(startdate) }) return ( <form onSubmit={handleSubmit(onSubmit)}> <div> <input id="firstname" name="firstname" type="text" { ...register("firstname") } /> </div> <div> <Controller control={control} name='startdate' render={({ field: { onChange, value } }) => ( <DateTimePicker onChange={onChange} selected={value} /> )} /> </div> </form> ) }
It looks like you are correct in using react-hook-form and react-datetime-picker. The problem you are facing may be related to the initial value of the date field being set incorrectly.
To solve this problem, you can use the defaultValue property in the Controller to set the initial value for the date field. Additionally, you should ensure that the value passed to DateTimePicker is a Date object, since react-datetime-picker expects a Date value.
The following is the updated code:
By setting defaultValue to new Date(), the date picker should now display the current date when the form first renders. Also, make sure that when passing the value to the DateTimePicker using new Date(value) it is a Date object.