Santhosh
Santhosh

Reputation: 11774

react hook form + material ui: Date Picker not getting the initial date

I and using React hook form. I have the following date picker Controller.

          <MuiPickersUtilsProvider utils={DateFnsUtils}>
            <Controller
              name="dateOfBirth"
              control={control}
              render={({ field: { ref, ...rest } }) => (
                <KeyboardDatePicker
                  ref={ref}
                  margin="dense"
                  fullWidth
                  id="date-picker-dialog"
                  label="Date picker dialog"
                  format="MM/dd/yyyy"
                  KeyboardButtonProps={{
                    "aria-label": "change date",
                  }}
                  {...rest}
                />
              )}
            />
          </MuiPickersUtilsProvider>

Now when I submit without changing the date it does not show dateOfBirth at all in the submit data.

BUt when I change the date then dateOfBirth is shown in the submit data

Upvotes: 1

Views: 3102

Answers (1)

knoefel
knoefel

Reputation: 6949

This is happening because you're not setting a defaultValue. When using <Controller /> it is required to provide a defaultValue, from the documentation:

You need to either provide defaultValue at the field-level or useForm with defaultValues.

One other minor thing: you should pass the ref to the inputRef of your <KeyboardDatePicker /> so RHF can link it to the actual input element.

Edit Material demo (forked)

Upvotes: 2

Related Questions