hypeserver / react-date-range

A React component for choosing dates and date ranges.
MIT License
2.57k stars 658 forks source link

not able to clear "days up to today" #531

Open pkvpraveen opened 2 years ago

pkvpraveen commented 2 years ago

Subject of the issue

If I want to input 9, I am not able to clear the field and enter 9. The last '1' stays.

[BUG] Bug Reproduce Steps

put the cursor in days up to today and try to enter 9.

[BUG] Expected behaviour

the field should be cleared and user can enter any number they want

Environment

Package Version: 1.4.0 React version: 16.13.1 Node version: 14.16.0 Browser: Firefox (v93)

thinkcodenyc commented 2 years ago

Weirdly enough we just ran into this same issue and have a working fix. The default code forces a 1 in the input field if you try to delete which is very frustrating UX.

See below for the modified defaultInputRanges array. Our example only has the days up to today in our form, so if you have multiple input ranges, make sure you're adding this specific object to your defaultInputRanges array.

Then when you render the component, you'll pass this constant to it. Code examples are below.

The modifications we added first check if there is a value.

By default, when you hit backspace to clear the form, the value is 0.

If there is a value, it returns the range as expected, with an additional object key called "clearField" set to false. If the value is 0, it returns today's date for start and end dates (to avoid breaking the form).

Then the getCurrentValue method checks for "clearField" to be set to true, and it returns an empty string, which renders a - in the field and allows typing you to type a new integer properly.

You can delete the console.logs as well, they're just there so you can better understand what's happening.

const defaultInputRanges = [ { label: "days up to today", range(value) { console.log("VALUE", value); if (value) { return { startDate: addDays( defineds.startOfToday, (Math.max(Number(value), 1) - 1) * -1 ), endDate: defineds.endOfToday, clearField: false, }; } return { startDate: new Date(), endDate: new Date(), clearField: true, }; }, getCurrentValue(range) { console.log("RANGE", range); if (range.clearField) return ""; if (!isSameDay(range.endDate, defineds.endOfToday)) return "-"; if (!range.startDate) return "∞"; return differenceInCalendarDays(defineds.endOfToday, range.startDate) + 1; }, }, ]

<DateRangePicker ranges={[state.selection]} onChange={handleSelect} maxDate={new Date()} inputRanges={defaultInputRanges} staticRanges={defaultStaticRanges} />