diff --git a/src/index.tsx b/src/index.tsx index ccd6ad996..c99641070 100644 --- a/src/index.tsx +++ b/src/index.tsx @@ -553,11 +553,20 @@ export default class DatePicker extends Component< this.cancelFocusInput(); }; + resetInputValue = () => { + this.setState({ + ...this.state, + inputValue: null, + }); + }; + handleBlur = (event: React.FocusEvent) => { if (!this.state.open || this.props.withPortal || this.props.showTimeInput) { this.props.onBlur?.(event); } + this.resetInputValue(); + if (this.state.open && this.props.open === false) { this.setOpen(false); } diff --git a/src/test/datepicker_test.test.tsx b/src/test/datepicker_test.test.tsx index 31e8890c6..966e3c824 100644 --- a/src/test/datepicker_test.test.tsx +++ b/src/test/datepicker_test.test.tsx @@ -4320,17 +4320,23 @@ describe("DatePicker", () => { }); describe("input reset", () => { - const renderDatePickerInput = () => { - const WrapperComponent = () => { + const renderDatePickerInput = (open: boolean | null = null) => { + const WrapperComponent = ({ open }: { open: boolean | null }) => { const [date, setDate] = useState(new Date()); - return ; + return ( + + ); }; - return render(); + return render(); }; it("should reset the date input element with the previously entered value element on blur even when the calendar open is false", () => { - const { container } = renderDatePickerInput(); + const { container } = renderDatePickerInput(false); const input = safeQuerySelector(container, "input") as HTMLInputElement; if (!input) { @@ -4357,6 +4363,36 @@ describe("DatePicker", () => { fireEvent.blur(input); expect(input.value).toBe(DATE_VALUE); }); + + it("should reset the date input element with the previously entered value on blur even when the calendar is not open", () => { + const { container } = renderDatePickerInput(); + const input = safeQuerySelector(container, "input") as HTMLInputElement; + + fireEvent.click(input); + + const VALID_DATE_VALUE = "06/23/2025"; + fireEvent.change(input, { + target: { + value: VALID_DATE_VALUE, + }, + }); + fireEvent.blur(input); + expect(input.value).toBe(VALID_DATE_VALUE); + + fireEvent.click(input); + fireEvent.keyDown(input, getKey(KeyType.Escape)); + // Make sure the calendar is hidden + expect(container.querySelector(".react-datepicker")).toBeFalsy(); + + const INVALID_DATE_VALUE = "2025-02-45"; + fireEvent.change(input, { + target: { + value: INVALID_DATE_VALUE, + }, + }); + fireEvent.blur(input); + expect(input.value).toBe(VALID_DATE_VALUE); + }); }); describe("Close on ESC Key", () => {