mantinedev / mantine

A fully featured React components library
https://mantine.dev
MIT License
26.34k stars 1.87k forks source link

DateInput `defaultDate` prop does not work when `value={null}` #4426

Open tofu2323 opened 1 year ago

tofu2323 commented 1 year ago

What package has an issue

@mantine/dates

Describe the bug

The defaultDate prop does not work on DateInput with useForm

What version of @mantine/hooks page do you have in package.json?

6.0.13

If possible, please include a link to a codesandbox with the reproduced problem

https://codesandbox.io/s/objective-lichterman-4qy3ml?file=/src/App.tsx

Do you know how to fix the issue

No

Are you willing to participate in fixing this issue and create a pull request with the fix

None

Possible fix

No response

AdamGEmerson commented 1 year ago

I'd like to take a stab at this if no one else is already working on it.

cyantree commented 1 year ago

@rtivital For DateInput what's the difference between defaultDate and defaultValue and between date and value.

@tofu2323 Why do you need defaultDate? Have you tried using the date in initialValues instead? Is it so that the field falls back to a specific date in case it has no value (or its value gets cleared)?

@AdamGEmerson Feel free to do so. :) I just had a quick look into the code but had difficulties understanding the meaning of the various props (see my question to rtivital).

cyantree commented 1 year ago

Also the docs say that defaultDate and defaultValue are meant for uncontrolled use which isn't the case with useForm(). https://mantine.dev/dates/date-input/?t=props https://mantine.dev/dates/date-picker-input/?t=props

AdamGEmerson commented 1 year ago

As @cyantree stated, the most likely issue is that these props are meant for uncontrolled input and useForm is controlled.

I also noticed playing with the example sandbox that the DatePicker component isn't "working" either. The defaultDate prop will continue to overwrite the input value even after form.getInputProps() is called with a valid Date set in initialValues.

See this example: Code Sandbox

One thing that might be worth addressing here is why the DateInput and DatePickerInput behave differently in this scenario. DatePickerInput responds with "Invalid Date", and DateInput just displays as empty. Is this expected behavior?

rajivchaulagain commented 3 months ago

@tofu2323 In my approach, I directly set the default date I need either in the value prop of the DateInput component or in the initialValues object when using useForm. This avoids setting the value to null first and then assigning the default date separately, which seems more straightforward and logical to me:

<DateInput value={new Date()} />
// or
const { register, handleSubmit, setValue } = useForm({
  initialValues: {
    date: new Date()
  }
});