I have a form element with a few inputs inside. 2 of these inputs are set to readOnly and have values passed in from a calendar element. If the input elements have a valid date in, they still say they have no value (by giving the error message field required) until the user either manually clicks them, tabs through them or just clicks the submit button a few times so they get focused automatically.
If anyone could help, please do suggest something!
Here is an example of one of my input elements (there is a start and end one with the only difference being the variable reference to each date in the array and naming of the input)
<Input
label="Start Date"
{...register("startDate", {
required: { value: true, message: "This field is required." },
})}
onClick={() =>
toast.error("Use the calendar to select a start date")
}
value={dates[0] ? dates[0].toLocaleDateString("fr-CA") : ""}
type="date"
readOnly
error={
typeof errors.startDate?.message === "string"
? errors.startDate?.message
: ""
}
/>
dates is type [Date | null, Date | null] (the dates are in the correct format and show up correctly)
and my <Input /> component
const Input = forwardRef<HTMLInputElement, InputProps>(
(
{
className,
error,
type,
disabled,
placeholder,
label,
secondary,
...props
},
ref
) => {
return (
<div className="flex flex-col gap-1">
<div className="flex gap-2">
{label && (
<label
className={
secondary ? "text-secondary text-lg" : "text-primary text-lg"
}>
{label}
</label>
)}
{error && <p className="text-error text-lg">*{error}</p>}
</div>
<input
type={type}
placeholder={placeholder}
disabled={disabled}
ref={ref}
{...props}
className={twMerge(
"bg-transparent border p-2",
secondary
? "border-secondary placeholder-secondary text-white"
: "border-primary text-black placeholder-primary",
className
)}
/>
</div>
);
}
);
>Solution :
I see that you are using react-hook-forms? you should use default values prop in useForm hook to pass the value to input or you should use setValue function to update the input value.