Nukodi
Nukodi

Reputation: 357

Formik Field with React-Datepicker issue

I am creating reusable fields for a dynamic form using Formik and its Field component.

I am having issues trying to implement React-Datepicker with the Field component. My issue is that when I put the date picker component into the Field component, I am unable to manually type the date I wish to enter. I am able to select the date directly from the calendar but I can't type the date. When I do try, it automatically fills in the date the 1st of the month that I typed (e.g. typing 2 gives 02/01/2021). However, validation is working and the value is being set, even though it is not the one I wanted.

When I move the date picker component outside of the Field component, it behaves normally but I am unable to access the errors and I cannot validate it with Formik. I am unsure what is causing the date picker to automatically complete.

I am fine with either using Field or not but I want to connect the date picker with Formik. I am able to use setFieldTouched and handleChange from Formik but setStatus and setFieldError hasn't been working either so I am unable to manually add the error.

Any ideas on what may be causing this? Am I connecting the two incorrectly?

<Field name='datepicker' as={datepickerComp} validate={validate} />

const [date, setDate] = React.useState(null)

React.useEffect(() => {
  handleChange({target: {name: 'datepicker', value: formattedDate(date)}})
}, [handleChange, date])

const onChangeHandler = (val) => {
  setFieldTouched('datepicker', true);
  setDate(val)
}

const datepickerComp = (props) => (
  <DatePicker 
    id="datepicker"
    name="datepicker"
    selected={date}
    onChange={onChangeHandler}
    required
  />
)

Upvotes: 0

Views: 3813

Answers (1)

Nukodi
Nukodi

Reputation: 357

So I do not know why using the as prop for Field causes the component to break. However, I found a work around using the date picker as a child component. It runs the validation and I am able to both select the date from the calendar and type in the date.

<Field name = "date" validate = {validate}>
  {({field, form, meta}) => (
    <DatePicker 
        name="date"
        selected={values.date || null}
        onChange(date => setFieldValue("date", date
      />
  )}
</Field>

Upvotes: 1

Related Questions