Reputation: 31
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 unfocusedvalidate
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?
Upvotes: 3
Views: 2259
Reputation: 266
According to the documentation, you can add the logic to the "inputProps" prop, since this takes in props to the input component, you can also add css to it as well.
inputProps Object : Additional props to add to the input component.
Your code will look like this:
const dateChanged = day => (console.log(day)); //function to call when date changes
inputProps={{
style: styles.dayPickerInput,
onChange: event => dateChanged(event.target.value),
}}
If you use onDayChange alone, it'll fire after the user "clicks" to select a day, not when the user actually types a date inside the input field, using this extra onchange listener will be a safeguard for you, if the input field is enabled for users to type in the date, which they might.
Upvotes: 0
Reputation: 5556
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>
Upvotes: 4