Venkata Penumatsa
Venkata Penumatsa

Reputation: 411

Fetching the default value of Material UI Date Picker when used with React Hook Forms

I am building a form using Material UI which contains 3 fields (1) Date (2) Hours (3) Comments. By default, the MUI Date picker field is defaulting to today's date. so when I populate the remaining fields (i.e. hours and comment) and submit the form, I am not seeing the Date value in my DATA object. instead, I have to explicitly select a calendar date and submit then the DATA object is populating with the date picker value.

this is causing an issue for me while submitting the data to database over a API call. anyone faced this type of issue..? how can i capture the date value properly in this scenario.

below is the code

import React, { useState } from "react";
import Grid from "@material-ui/core/Grid";
import TextField from "@material-ui/core/TextField";
import Button from "@material-ui/core/Button";
import DateFnsUtils from "@date-io/date-fns";
import {
  MuiPickersUtilsProvider,
  KeyboardTimePicker,
  KeyboardDatePicker,
} from "@material-ui/pickers";
import { useForm, Controller } from "react-hook-form";
import AddTime from "./AddTime";


export default function Form({ user }) {

  const { handleSubmit, control, reset } = useForm({});
  const onSubmit = (data) => console.log(data);


  return (
    <React.Fragment>
      <form onSubmit={handleSubmit(onSubmit)}>
        <Grid container spacing={3}>
          <Grid item xs={12} sm={6}>
            <MuiPickersUtilsProvider utils={DateFnsUtils}>
              <Controller
                name="date"
                control={control}
                render={({ field: { ref, ...rest } }) => (
                  <KeyboardDatePicker
                    margin="none"
                    id="date-picker-dialog"
                    label="Select date"
                    format="MM/dd/yyyy"
                    KeyboardButtonProps={{
                      "aria-label": "change date",
                    }}
                    {...rest}
                  />
                )}
              />
            </MuiPickersUtilsProvider>
          </Grid>
          <Grid item xs={12} sm={6}>
            <Controller
              render={({ field, fieldState: { error } }) => (
                <TextField
                  {...field}
                  label="Enter Hours"
                  variant="standard"
                  size="small"
                  error={!!error}
                  helperText={error ? error.message : null}
                />
              )}
              name="hours"
              control={control}
              rules={{ required: "Enter Hours" }}
            />
          </Grid>
          <Grid item xs={12}>
            <Controller
              render={({ field, fieldState: { error } }) => (
                <TextField
                  {...field}
                  label="Enter Comments if any"
                  variant="standard"
                  size="small"
                  multiline
                  fullWidth
                  error={!!error}
                  helperText={error ? error.message : null}
                />
              )}
              name="comment"
              rules={{ required: "Enter Comments" }}
              control={control}
            />
          </Grid>
          <Grid item xs={12}>
            <Button
              variant="contained"
              color="primary"
              type="submit"
              size="small"
            >
              submit
            </Button>
            <br />
            <br />
            <Button
              variant="contained"
              color="primary"
              size="small"
              onClick={() => {
                reset({
                  date: new Date(),
                  hours: "",
                  comment: "",
                });
              }}
            >
              Reset Form
            </Button>
          </Grid>
        </Grid>{" "}
      </form>
    </React.Fragment>
  );
}

Below is the screenshot of the console log. when I click on submit, date is showing as undefined

enter image description here

when I manually change the date and submit, then it's populating fine.

Thanks In Advance - Venkata Penumatsa

Upvotes: 0

Views: 7486

Answers (1)

knoefel
knoefel

Reputation: 6989

The problem is you're not setting a defaultValue for your <Controller /> components. This is required for external controlled components like Material UI components.

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

Here is the relevant section in the documentation.

Edit React Hook Form - Basic (forked)

Upvotes: 2

Related Questions