Help with implementing DateInput on Form

1 Answer 17 Views
DatePicker Form
smd
Top achievements
Rank 1
Iron
Iron
smd asked on 25 Mar 2025, 04:42 PM

Hi, 

My form is going to have controlled DatePicker component. However, I could not figure out why when I defined the onChange function on the DatePicker, the form submission excluded its value. 

https://codesandbox.io/p/sandbox/cool-hofstadter-2vj2s3?file=%2Fapp%2Fapp.jsx%3A18%2C7

From the code above, Test Date 1 and Test Date 2 components are almost the same, except, Test Date 2 component has line 63, which I set its 'value' and defined 'onChange' function separately. However, form submission will not recognize Test Date 2 value. 

From pictures above, if removing 'value' and 'onChange' on line 63, you will see Result on the left, otherwise, you will receive result on the right

1 Answer, 1 is accepted

Sort by
0
Vessy
Telerik team
answered on 27 Mar 2025, 03:06 PM

Hi,

The issue you're experiencing with the Test Date 2 component is related to the fact when a component is used in controlled mode it uses separate state therefore the form is not aware of its changes.

To ensure that the form submission includes the value of the second DatePicker,  you need to update the form state whenever the date changes. Here's how you can modify your code:

              <Field
                name="testDate2"
                component={(props) => {
                  return (
                    <DatePicker
                      value={dateValue2} // Controlled by state
                      onChange={(event) => {
                        setDateValue2(event.value); // Update local state
                        props.onChange({ value: event.value }); // Explicitly update Form state
                      }}
                    />
                  );
                }}
              />

I hope this helps.

Regards,
Vessy
Progress Telerik

Enjoyed our products? Share your experience on G2 and receive a $25 Amazon gift card for a limited time!

smd
Top achievements
Rank 1
Iron
Iron
commented on 27 Mar 2025, 04:37 PM

This is great. Thank you, Vessy. I had been puzzled by this for a couple days, even redesigning my form for a workaround but it always came back to this. 
Vessy
Telerik team
commented on 28 Mar 2025, 12:34 PM

You are most welcome, I am glad my suggestion was helpful :)
Tags
DatePicker Form
Asked by
smd
Top achievements
Rank 1
Iron
Iron
Answers by
Vessy
Telerik team
Share this question
or