Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Adding onChange logic to third-party react-day-picker element

I'm trying to integrate react-day-picker's DayPicker with react-final-form.

React Final Form requires the use of a Field for each form field, which means creating an adapter component whenever you want to a third-party form element to be usable within the form. The adapter component has to accept an input object containing value and onChange. The advice is just to provide a new onChange.

This approach, which works for many other components, doesn't work for DayPicker. It seems like the issue is that DayPicker doesn't actually have an onChange method, so it's up to us to manage what happens when the calendar changes and then store the dates in value property that react-final-form expects.

I've created a codepen here: https://codesandbox.io/s/github/pcraig3/date-picker-sandbox

I have a handleDayClick method in Calendar.js which runs when days are clicked, but onChange isn't being triggered for the calendar consistently.

  • selectedDays is being updated immediately within the Calendar itself, but the Form is not getting the correct dates until the calendar is unfocused
  • The form's validate method is only being called once (the first time selecting a day), whereas it is called each time the native text input value is updated.

I would like the form values to be synced up with the calendar's external state and for the validate method to be triggered each time a day is clicked/unclicked. Is this possible to achieve or am I doing completely the wrong thing?

like image 708
Paul Craig Avatar asked Dec 08 '25 20:12

Paul Craig


1 Answers

It's probably easier to use the <DayPickerInput> component, instead. That component uses a standard HTML input, which supports onChange. I did it like this:

<Field name={id}>
  {({ input, meta }) => (
    <React.Fragment>
      <label htmlFor={id}>Date: </label>
      <DayPickerInput
        {...input}
        onDayChange={day => input.onChange(day)}
        inputProps={{ id: id }}
      />
      {meta.error && meta.touched && <div className="error">{meta.error}</div>}
    </React.Fragment>
  )}
</Field>
like image 57
singingwolfboy Avatar answered Dec 10 '25 11:12

singingwolfboy