MUI DatePicker not working correctly with Formik

Viewed 2751

I am using Formik in my React project to process forms and using MUI UI components.

I am able to pick the day, month, but the year part does not change. If I manually type in year in the textfield, the year part is not reflected in the changed state.

Here's my code:

                 <LocalizationProvider dateAdapter={DateAdapter}>
                   <DatePicker
                     name="birthday"
                     id="birthday"
                     variant="standard"
                     label="Birthday"
                     value={formik.values.birthday}
                     renderInput={(params) => (
                       <TextField {...params} variant="standard" fullWidth/>
                     )}
                     onChange={(value) => formik.setFieldValue('birthday', value, true)}
                     error={formik.touched.birthday && Boolean(formik.errors.birthday)}
                     helperText={formik.touched.birthday && formik.errors.birthday}
                   />
                 </LocalizationProvider>

The initial state:

const initialFormState = {
  birthday: Date.now(),
};

All the other components are working correctly and changes in state show immediately.

1 Answers

The onChange property is not set in the DatePicker component. You have to move the onChange property from TextField to DatePicker.

<LocalizationProvider dateAdapter={AdapterDateFns}>
   <DatePicker
      onChange={(value) => setFieldValue("birthday", value, true)}
      value={values.birthday}
      renderInput={(params) => (
      <TextField
        error={Boolean(touched.birthday && errors.birthday)}
        helperText={touched.birthday && errors.birthday}
        label="Birthday"
        margin="normal"
        name="birthday"
        variant="standard"
        fullWidth
        {...params}
       />
       )}
      />
  </LocalizationProvider>

Also, the name, id, variant and label are TextField's properties.

Here is the working CodeSandbox link.

Related