Getting error as 'handleChange is not a function' while selecting date in Material UI

Viewed 257

On selecting specific date in DatePicker component, getting error as 'handleChange is not a function' as mentioned above. DatePicker component is wrapped in Controller component of react-hook-form. Expected to display date on DatePicker input. How could it be resolved? See the code below:

<form noValidate autoComplete="off" onSubmit={handleSubmit(onSubmit)}>
        <Controller
          control={control}
          name="date"
          render={({ handleDateChange, selectedDate, ref }) => (
            <>
              <MuiPickersUtilsProvider utils={DateFnsUtils}>
                <Grid container justify="space-around">
                  <DatePicker
                    ref={ref}
                    value={selectedDate}
                    onChange={handleDateChange}
                    format={`d  |  ` + `MMMM  |  ` + `yyyy`}
                    disablePast
                    animateYearScrolling
                    margin="normal"
                    style={{ cursor: "pointer" }}
                  />
                </Grid>
              </MuiPickersUtilsProvider>

              <br />
            </>
          )}
          rules={{
            required: "Date is required"
          }}
        />
      </form>

Here is the CodeSandbox link: https://codesandbox.io/s/jolly-currying-lwtrj

Any suggestion or code changes is highly appreciated.

1 Answers

Firstly, there is no such properties as handleDateChange or selectedDate, perhaps this is what you mean:

render={({ onChange: handleDateChange, value: selectedDate, ref }) => (

Secondly, you're using react-hook-form v7, the render method signature of Controller was changed. See the migration guide here. You need to get the input props from the field property, not directly from the render props:

render={({ field }) => {
  const {
    onChange: handleDateChange,
    value: selectedDate,
    ref
  } = field;

Full working code:

<Controller
  control={control}
  name="date"
  render={({ field }) => {
    const {
      onChange: handleDateChange,
      value: selectedDate,
      ref
    } = field;
    return (
      <>
        <MuiPickersUtilsProvider utils={DateFnsUtils}>
          <Grid container justify="space-around">
            <DatePicker
              ref={ref}
              value={selectedDate}
              onChange={handleDateChange}
              format={`d  |  ` + `MMMM  |  ` + `yyyy`}
              disablePast
              animateYearScrolling
              margin="normal"
              style={{ cursor: "pointer" }}
            />
          </Grid>
        </MuiPickersUtilsProvider>

        <br />
      </>
    );
  }}
  rules={{
    required: "Date is required"
  }}
/>

Live Demo

Edit 67200152/getting-error-as-handlechange-is-not-a-function-while-selecting-date-in-materi

Related