Skip to content

Commit bced65d

Browse files
fix: update preSelection when input changes for selectsRange
When using selectsRange with input field changes, the preSelection state was not being updated. This caused inconsistent calendar viewport behavior when closing and reopening the datepicker after changing dates via input vs via calendar click. The fix updates preSelection to the new startDate when processing input changes for range selection, matching the behavior of calcInitialState. Fixes #5916 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-Authored-By: Claude <noreply@anthropic.com>
1 parent de1e0c1 commit bced65d

2 files changed

Lines changed: 39 additions & 0 deletions

File tree

src/index.tsx

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -725,6 +725,12 @@ export class DatePicker extends Component<DatePickerProps, DatePickerState> {
725725
return;
726726
}
727727

728+
// Update preSelection to keep calendar viewport consistent when reopening
729+
// Use startDate for preSelection to match calcInitialState behavior
730+
if (startDateNew) {
731+
this.setState({ preSelection: startDateNew });
732+
}
733+
728734
this.props.onChange?.([startDateNew, endDateNew], event);
729735
} else {
730736
// not selectsRange

src/test/datepicker_test.test.tsx

Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2337,6 +2337,39 @@ describe("DatePicker", () => {
23372337

23382338
expect(onChangeSpy.mock.calls.at(-1)[0]).toStrictEqual([null, null]);
23392339
});
2340+
it("should update preSelection when input changes for selectsRange", () => {
2341+
let instance: DatePicker | null = null;
2342+
const onChangeSpy = jest.fn();
2343+
2344+
render(
2345+
<DatePicker
2346+
ref={(node) => {
2347+
instance = node;
2348+
}}
2349+
selectsRange
2350+
startDate={newDate("2024-01-15")}
2351+
endDate={newDate("2024-01-20")}
2352+
onChange={onChangeSpy}
2353+
dateFormat="MM/dd/yyyy"
2354+
/>,
2355+
);
2356+
expect(instance).toBeTruthy();
2357+
2358+
// Get initial preSelection
2359+
const initialPreSelection = instance!.state.preSelection;
2360+
2361+
// Change the date via input
2362+
fireEvent.change(instance!.input!, {
2363+
target: {
2364+
value: "02/10/2024 - 02/15/2024",
2365+
},
2366+
});
2367+
2368+
// preSelection should be updated to the new start date
2369+
expect(instance!.state.preSelection).not.toEqual(initialPreSelection);
2370+
expect(instance!.state.preSelection?.getMonth()).toBe(1); // February (0-indexed)
2371+
expect(instance!.state.preSelection?.getDate()).toBe(10);
2372+
});
23402373
it("should correctly update the input when the value prop changes", () => {
23412374
let instance: DatePicker | null = null;
23422375
const { rerender } = render(

0 commit comments

Comments
 (0)