How to set default date for value as date? #4718
-
<input
type="date"
id="date"
{...register("date", {
valueAsDate: true,
})}
defaultValue={new Date()}
/> How do I set todays date as default value for date field? The above code has error on line default value |
Beta Was this translation helpful? Give feedback.
Replies: 3 comments 5 replies
-
The date format for https://developer.mozilla.org/en-US/docs/Web/HTML/Element/Input/date#value |
Beta Was this translation helpful? Give feedback.
-
This feels very iffy, but I have this hack: function isValidDate(date: Date) {
return !isNaN(date.getTime());
}
type Maybe<T> = T | undefined | null;
/**
* Create a date YYYY-MM-DD date string that is typecasted as a `Date`.
* Hack when using `defaultValues` in `react-hook-form`
* This is because `react-hook-form` doesn't support `defaultValue` of type `Date` even if the types say so
*/
export function dateToInputDate(date: Maybe<Date>) {
if (!date || !isValidDate(date)) {
return undefined;
}
return date.toJSON().slice(0, 10) as unknown as Date;
} |
Beta Was this translation helpful? Give feedback.
-
// step 2) and use the default in the register from ther form |
Beta Was this translation helpful? Give feedback.
The date format for
value
anddefaultValue
should beYYYY-MM-DD
https://developer.mozilla.org/en-US/docs/Web/HTML/Element/Input/date#value