flowbite-react
flowbite-react copied to clipboard
Allow Datepicker to be empty
Summary
Datepicker only allows to receive a valid Date but it would be really great if we could set null
, ""
or any kind of value that represents empty.
Context
So, i was working in specific use case where users can set a Date but this field is optional (null under the hood), so the user can also keep it empty.
When i start this i saw Clear button and i tought this was exactly what i was looking for but then i realize that this button only resets the field to defaultDate
or minDate
but never to ""
(as native input does) or null
. Since Clear button resets to defaultDate
, would be great if defaultDate accepts null
or even if onSeletedDateChanged
could receive the current value and a second boolean prop like isClearAction
so we can customize the logic.
For now, since im using React Hook Form to deal with validations, i've reached this by using the following approach:
type MyDatepickerProps = Omit<
DatepickerProps,
'showClearButton' | 'labelClearButton'
> & {
onClear?: () => void;
};
const MyDatepicker = forwardRef<
DatepickerRef,
MyDatepickerDatepickerProps
>(({ onClear, ...rest }, ref) => {
return (
<div>
<Datepicker
ref={ref}
{...rest}
showClearButton={!onClear}
labelClearButton="Reset"
/>
{onClear && (
<button
onClick={onClear}
type="button"
>
{/* This is just a X icon for the button */}
<HiXCircle />
</button>
)}
</div>
);
});
And in the form (remember: im using React Hook Form):
<Controller
control={control}
name="my-field"
render={({ field }) => (
<MyDatepicker
minDate={new Date()}
value={field.value === null ? '' : field.value?.toDateString()}
placeholder="Date"
onSelectedDateChanged={field.onChange}
onClear={() => field.onChange(null)}
/>
)}
/>;
As you can see, im not using default onChange
since it not triggers with current value. Thats why im using Controller
to customize field actions.
Would be very very good to have this behavior on this component 🥺
EDIT: I've already read some issues about that but this is a feature request since it is not implemented.
Upvoting and commenting - this would be a nice and logic evolution 🙏
Agreed, this should be possible
This is needed!